Skip to content

Instantly share code, notes, and snippets.

@ahmed-bacha
Last active August 29, 2015 14:14
Show Gist options
  • Save ahmed-bacha/198c9bcd311f9aaceb5f to your computer and use it in GitHub Desktop.
Save ahmed-bacha/198c9bcd311f9aaceb5f to your computer and use it in GitHub Desktop.
Using session variables in a JEE Servlet (ADD variable/GET variable from session scope)

Using session variables in a JEE (Servlet)

Open the session first !


Open a session in a JEE Servlet (to do each time, in all Servlets that you want to access to Session variables)

// GET the current session from the request
HttpSession session 		= 	request.getSession();

Set/Add a variable to the current session


In a JEE Servlet or JSP with <% %> tags, *** Session must be opened before! ***

// ADD a variable (User in this case) to a session
session.setAttribute("user", user);

Get a variable from the current session


In a JEE Servlet or JSP with <% %> tags, , *** Session must be opened before! ***

// GET a variable (User in this case) from the  session 
User 		user		= 	(User) session.getAttribute("user");

Delete a variable from the current session

In a JEE Servlet or JSP with <% %> tags, , *** Session must be opened before! ***

// Delete a variable (User in this case) from the  session 
session.removeAttribute("user");

Destroy the current session

In a JEE Servlet or JSP with <% %> tags, , *** Session must be opened before! ***

// To destroy the current session
session.invalidate();

Enjoy !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment