How to manage Sessions in Servlets

As known, HTTP Protocol is stateless, that means it does not store any session related information during the interaction between Web Browser and Web Server. HTTP Protocol just sends a request to Web Server, and receives response HTML page. But HTTP does not itself maintain any session information such as which user is currently browsing, etc…

Generally, a new session need to be created when user successfully logs in, and this user specific session data is being maintained, through out user interaction with various web pages. Finally when user logs out, the session need to be destroyed.
So it is responsibility of Server side program(like Java Servlets) to maintain session related information.

In case of Java, Servlets or JSP facilitates, to create, destroy, set and get values of Session. For this purpose javax.servlet.http.HttpSession class has been provided.

Why and when session is required

A session stores user specific data, when user is interacting with the web site. Not all the Servlets need sessions. Generally all Web sites with User login facility need to maintain session.


How to create a session: Session can be created by invoking
getSession() method in HttpServletRequest class. Below are two overloaded methods of getSession()
1.getSession(): This method has no parameters, and is always used to create new session.
2.getSession(boolean ):This method need to be invoked with true, to create a new session, and false to retrieve existing session which is in progress, and session which has been already created in previous servlets.

Below is description of few methods declared in javax.servlet.http.HttpSession
Once the session is created, below operations can be performed
1.void setAttribute(String attr_name, Object obj); is invoked to set an attribute name and value, so that this value can be retrieved[by invoking getAttribute(String attr_name) method] in other servlets

Object getAttribute(String attr_name); is invoked to retrieve a value which has already been set to the session, by invoking setAttribute(String attr_name, Object obj);

Any User’s data can be stored in session, You can set and get any object in the session.
But be aware that, saving huge data in the session, may adversely affect your Web Application’s performance.
By default, session data is stored temporarily during web application’s execution and session data does not get stored persistently.
Though session data is stored on server side, it is good practice not to store confidential data in session.

3.session.removeAttribute(“attribute_name”); removes or deletes an attribute’s object from the session. You can use this method, when a specific attribute is more required. Other attributes remains intact in the session.

How to set session idle timeout

3.When no methods of session are invoked for certain period, automatically session gets destroyed.
setMaxInactiveInterval(int interval); interval in seconds

How to Destroy a session

4.When user tries to log out, invalidate() method of HttpSession is invoked to destroy the session which is in progress. After the session is destroyed, no session data is available.

Below are simple snippets, showing on how to create/destroy sessions, and how to get and put values into HttpSession.

Below is an HTML page, which invokes HttpSessionDemo servlet, when submitted.

        <title>Session Demo</title>
        <form action="HttpSessionDemo">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  

Below Servlet receives userName submitted by above html form, then creates a new session, then sets the username to uname attribute. Also provides an hyper link Visit, when clicked HttpSessionDemo1 Servlet is displayed

import javax.servlet.*;  
import javax.servlet.http.*;  
public class HttpSessionDemo extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response){  
        PrintWriter out = response.getWriter();  
        String n=request.getParameter("userName");  
        out.print("Welcome "+n);  
        //create new session
        HttpSession session=request.getSession();
        //set the attribute uname to the session
        //which can be further retrieved, in other servlets
        //as long as session is valid
        //Attribute value can be of any type, since Object is expected parameter
        //setMaxInactiveInterval(int interval), 
        //container invalidates session, if no requests from client, for a certain time(in seconds)
                }catch(Exception e){System.out.println(e);}  

Below Servlet is processed, when Visit hyper is clicked, this servlet gets the existing session, also gets uname attribute from session, then displays uname value. Finally destroys session and it’s data by invoking sesison.inValidate()

import javax.servlet.*;  
import javax.servlet.http.*;  
public class HttpSessionDemo1 extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        PrintWriter out = response.getWriter();  
        //retrieve existing session, hence false parameter is sent
        HttpSession session=request.getSession(false); 
        //retrieve the attribute uname, from the session
        String n=(String)session.getAttribute("uname");  
        out.print("Hello "+n);  
        //invoke removeAttribute() if you want to remove any attribute
        //stored in the session
        //use invalidate method to completely destroy current session
        //so that it doesn't exist any more
                }catch(Exception e){System.out.println(e);}  

However, for database backed sessions, may be more useful when a web application is deployed across multiple servers, and client requests are managed by Load Balancer.

You may also like to read:

How to use multiple Servlet Filters
How many implicit java objects are there in JSP
Servlet Life Cycle