Http Session Management – HttpSession

HttpSession is used to save user session related information. It is provided by servlet API. When a session request come to a servlet container, it will create a HttpSession object at server side and then assign a unique id to it. The session id will be returned back to client browser, and it will be saved either by cookie or request url parameter. So when the client request to web server again, it will send the session id back to web server also. Then web server will know whom the client is by the session id and it stored value.

httpsession structure

HttpServletRequest interface’s methods to obtain HttpSession object:

public HttpSession getSession():Returns the existing HttpSession object related to this request. If the value is null then create and return a new one.

public HttpSession getSession(boolean create):Returns the existing HttpSession object related to this request. If the value is null and the input parameter “create” is true then create a new session object to return.

Other important methods

Object getAttribute(String name): Returns the saved object in this HttpSession object with the specified object name, or null if there is no object found with the name. HttpSession’s other methods to manage attributes are setAttribute(String name, Object value), removeAttribute(String name) and getAttributeNames().

String getId(): Returns a unique identifier string assigned to current HttpSession object. This is also called JSESSIONID, it will be saved at client cookie or request url.

ServletContext getServletContext():  Returns the web applicaion’s ServletContext object. This is an application scope object. You can save information in it when you want to use the stored data throughout the whole web application.

long getCreationTime(): Returns current HttpSession create time in milliseconds from January 1, 1970 GMT.

long getLastAccessedTime(): Return the last access time of current HttpSession object.

getMaxInactiveInterval(): Get the max inactive seconds between two request in the same HttpSession.

setMaxInactiveInterval(int interval): Set the max inactive seconds between two request in the same session. If timeout then the session will be removed by servlet container.

READ :   Hello World Example Use Servlet

void invalidate(): Make the session invalidate and remove all it’s stored object.

JSESSIONID

JSESSIONID is the unique identifier related to current HttpSession. It is created by servlet container when you use HttpServletRequest getSession() method to create a session object. It’s value is sent back and saved to client by cookie. If client side disable cookie then we use url rewriting to save it’s value in request url parameter.

Sessions and Clusters

If you have a cluster with two or more web servers, remember that one server saved session object values is probably not available in the other server. So, in case when the cluster divide a client’s requests between two or more servers, occasionally session values might be lost.

The solution for this issue:

  1. Use a database to store session attributes value. Then all servers in the cluster can read, write same data from the database.
  2. Use a session server, all the session related data and events will be sent to this server to verify and manage. It is something like database but it is more fast than db because all the operation will be handled in memory.

HttpSession Advantage

  1. Secure. All data will operate at server side.
  2. Make java code simple and clear.
  3. Can store session object values data in file or db.
  4. When used in cluster, a session server can be used to manipulate session issues for request from all the servers in the cluster.
  5. Do not rely on cookie, can still work if client disable cookie.

Example

This is a user register system implemented with HttpSession.

  1. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserAccount.jsp
    Allow user to enter user name and password.
  2. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserEmail.jsp
    Allow user to enter email.
  3. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionFinishRegister.jsp
    User confirm entered information in this page.
  4. com.dev2qa.example.servletsession.SessionManageHttpSession
    The servlet for logic verification and page navigation.

Source Codes

  1. /pages/regist/httpSessionInputUserAccount.jsp

    Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserAccount.jsp
    httpsession example input username and password

    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="inputUserAccount" />
    UserName: <input type="text" id="userName" name="userName"/><br/>
    Password: <input type="password" id="password" name="password"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  2. /pages/regist/httpSessionInputUserEmail.jsp
    httpsession example input user email

    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="inputUserEmail" />
    Email: <input type="text" id="email" name="email"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  3. /pages/regist/httpSessionFinishRegister.jsp
    User confirm page.
    httpsession example user confirm page not click Invalidate This Session link
    If use click “Invalidate This Session” link then show below page.
    httpsession example user confirm page after click invalidate this session link

    <%
    String userName = "";
    String password = "";
    String email = "";
    /* Get below data from HttpSession. */
    HttpSession reqSession = request.getSession();
    
    String JSESSIONID = reqSession.getId();
    
    Object userNameObj = reqSession.getAttribute("userName");
    Object passwordObj = reqSession.getAttribute("password");
    Object emailObj = reqSession.getAttribute("email");
    
    /*Get the message object form HttpServletRequest. */
    String message = request.getParameter("message");
    if(message==null)
    {
    	message = "";
    }
    
    if(userNameObj!=null)
    {
    	userName = (String)userNameObj;
    }
    
    if(passwordObj!=null)
    {
    	password = (String)passwordObj;
    }
    
    if(emailObj!=null)
    {
    	email = (String)emailObj;
    }
    
    %>
    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="finishRegister" />
    <%=message %><br/><br/>
    JSESSIONID: <%=JSESSIONID %><br/><br/>
    Please confirm below user information then click Finish button to register.<br/><br/>
    User Name: <%=userName %><br/>
    Password: <%=password %><br/>
    Email: <%=email %><br/>
    <input type="submit" value="Finish"/>
    </form>
    
    Click <a href="/Dev2qaWebAppExample/SessionManageHttpSession?action=invalidateSession">Invalidate This Session</a> to invalidate and remove all the stoerd data value in it.
    
  4. com.dev2qa.example.servletsession.SessionManageHttpSession
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		/* Use action value to check current step page.*/
    		String action = req.getParameter("action");
    		
    		boolean needForward = true;
    		String targetUrl = "";
    		if("inputUserAccount".equalsIgnoreCase(action))
    		{
    			/* Get below data from user input text box.*/
    			String userName = req.getParameter("userName");
    			String password = req.getParameter("password");
    			
    			HttpSession reqSession = req.getSession(true);
    			reqSession.setAttribute("userName", userName);
    			reqSession.setAttribute("password", password);
    			
    			targetUrl = "/pages/regist/httpSessionInputUserEmail.jsp";
    		}else if("inputUserEmail".equalsIgnoreCase(action))
    		{			
    			/* Get email from user input text box. */
    			String email = req.getParameter("email");
    			
    			HttpSession reqSession = req.getSession(true);
    			reqSession.setAttribute("email", email);
    			
    			targetUrl = "/pages/regist/httpSessionFinishRegister.jsp";
    		}else if("finishRegister".equalsIgnoreCase(action))
    		{
    			String JSESSIONID = "";
    			String userName = "";
    			String password = "";
    			String email = "";
    		
    			HttpSession reqSession = req.getSession(true);
    			
    			JSESSIONID = reqSession.getId();
    			
    			Object userNameObj = reqSession.getAttribute("userName");
    			Object passwordObj = reqSession.getAttribute("password");
    			Object emailObj = reqSession.getAttribute("email");
    			
    			if(userNameObj!=null)
    			{
    				userName = (String)userNameObj;
    			}
    			
    			if(passwordObj!=null)
    			{
    				password = (String)passwordObj;
    			}
    			
    			if(emailObj!=null)
    			{
    				email = (String)emailObj;
    			}
    			
    			PrintWriter pw = resp.getWriter();
    			pw.println("JSESSIONID : " + JSESSIONID);
    			pw.println("User Name : " + userName);
    			pw.println("Password : " + password);
    			pw.println("Email : " + email);
    			pw.println("Your user information has been registered successful.");
    			needForward = false;
    		}else if("invalidateSession".equals(action))
    		{
    			HttpSession reqSession = req.getSession(true);
    			String JSESSIONID = reqSession.getId();
    			
    			reqSession.invalidate();
    			
    			String errMessage = "Session has been invalidate, JSESSION id is " + JSESSIONID + ", the value stored in this session had been removed.";
    			
    			/* Save the error message in request url parameter. Because reqSession has been invalidate, if call it again there will throws an exception.*/
    			targetUrl = "/pages/regist/httpSessionFinishRegister.jsp?message="+errMessage;
    		}else
    		{
    			/* No action request parameter then go to first page of register*/
    			targetUrl = "/pages/regist/httpSessionInputUserAccount.jsp";
    		}
    		
    		if(needForward)
    		{
    			/* 
    		     We need to get the web application context path as the root path of each next page url.
    			 * */
    			String contextPath = this.getServletContext().getContextPath();
    			resp.sendRedirect(contextPath + targetUrl);
    		}
    	}

     

Download “Http-Session-Management-HttpSession-Example-Code.zip” Http-Session-Management-HttpSession-Example-Code.zip – Downloaded 60 times – 60 KB

(Visited 257 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.