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.

http-session
http-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

2.
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.

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

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 java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class HttpSessionDemo extends HttpServlet {  
  
public void doGet(HttpServletRequest request, HttpServletResponse response){  
        try{  
  
        response.setContentType("text/html");  
        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
        session.setAttribute("uname",n);  
        
        //setMaxInactiveInterval(int interval), 
        //container invalidates session, if no requests from client, for a certain time(in seconds)
  
        out.print("visit");  
                  
        out.close();  
  
                }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 java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class HttpSessionDemo1 extends HttpServlet {  
  
    @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)  
{
        try{  
  
        response.setContentType("text/html");  
        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
        //session.removeAttribute("attribute_name");
        
        //use invalidate method to completely destroy current session
        //so that it doesn't exist any more
        session.invalidate();      
        
        out.close();  
  
                }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

Java Servlet and Life Cycle

A Servlet is a Java Program, which runs on any Web Server(Tomcat Server, Glass Fish Server, Web Logic, Web Sphere). Servlet receives request from Web Browser on Client Machine. Below are Life cycle methods for a Servlet.

public void init(ServletConfig config);
This method is invoked when Servlet instance does not exist, and on receiving first request from Web Browser. init() method is not invoked, for each and every request. Constructor of Servlet is executed before init() method.

public void service(ServletRequest request, ServletResponse response);
This method is invoked, whenever a request is received from Web Browser. This method processes, and provides response to the Request. This method further invokes doGet() or doPost() method, based on GET or POST HTTP Request.

public void destroy();
This method is invoked, when Servlet instance gets destroyed, which may occur, when no requests, or when Web Server is shutdown, or garbage collection, to reclaim memory,etc…

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LifeCycle extends HttpServlet
{

	public LifeCycle()
	{
		System.out.println("Am from default constructor");
	}

	public void init(ServletConfig config)
	{
		System.out.println("Am from Init method...!");
	}

        public void doGet(HttpServletRequest req,HttpServletResponse res)
                throws ServletException,IOException
        {
            System.out.println("Am from doGet method...!");
            PrintWriter out = res.getWriter();

            out.println(" from doGet()
"); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { System.out.println("Am from doPost method...!"); PrintWriter out = res.getWriter(); out.println(" from doPost()
"); } public void destroy() { System.out.println("Am from Destroy methods"); } } Output(on Server Console, when request is sent to Web Server): INFO: Am from default constructor INFO: Am from Init method...! INFO: Am from doGet method...!

It is required to be aware of Servlet Life Cycle methods, to develop efficient Java Servlets.

You may also like to read:
Purpose of Filter in Servlets
How many implicit objects are in JSP
Program to send HTTP Request to Web Server

Can we have multiple Servlet Filters?

As already briefed in Servlet , a Servlet is a Server Side Java Program, which runs on Web Server or Application Server, and provides HTTP response to the HTTP request received from a Web Browser, such as Filter does Preprocessing and post processing

A Servlet Filter is used to perform pre processing and post processing a request to a servlet.

How Servlet Filter can be used

Below are few scenarios where Filters can be used
1. To decrypt a request(received , and to encrypt response(before sending to client/browser)
2. For profiling purpose, how much time server takes to process a request, and respond.
3. To log client IP address, in a file or to a database table.
4. To block requests from certain range of IP address.

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

Filter interface
Methods in Filter interface, which need to be implemented.

Deployment Descriptor web.xml

Multiple filters can be configured

Advantages of Servlet Filter

Filters are dynamically pluggable.
They can be plugged in, plugged out , without any source code changes.
Filter
Plugging and need not go through development cycle, and hence

How to configure Filter in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <filter>
    <filter-name>MyFilter

Filter example

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();

   //Do not process request from local host
    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("<br>myfilter is invoked before");
    chain.doFilter(req, resp);//sends request to next resource

    out.print("<br>myfilter is invoked after");

    System.out.println("doFilter() in MyFilter");
    }

public void destroy() {
    System.out.println("destroy() in MyFilter");
    }
}

servlet code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NewServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<br>welcome to servlet<br>");
    }
}

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

How to configure multiple Filters to a Servlet?

Yes, it is possible to have multiple Filters, which need to be configured in Deployment Descriptor(web.xml). The order in which these filters get invoked is the order in which they are configured in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

        <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>NewFilter</filter-name>
        <filter-class>NewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>NewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Below is an example of Web.xml, which has below two Filters

1. MyFilter.java - Logs Clients IP Address to Server Console, similarly,

Below is source code of NewFilter.java


Below is source code of MyFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();


    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("
myfilter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
myfilter is invoked after"); System.out.println("doFilter() in MyFilter"); } public void destroy() { System.out.println("destroy() in MyFilter"); } }

2. NewFilter.java - Just prints log on Web Server Console

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class NewFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in NewFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();
    out.print("
filter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
filter is invoked after"); System.out.println("doFilter() in NewFilter"); } public void destroy() { System.out.println("destroy() in NewFilter"); } }

No Source code changes are required in the servlet.

How to map Filter to a specific URLs or Servlet(s)?

It is possible to map Filters to a specific URLS or Servlet(s). This is possible by adjusting means it Filter gets invoked for all Servlets. By chaging it to below

Filter gets invoked only when urls starting with abc are requested, from Web Browser

    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

You may also like to read:
What is Servlet Life Cycle?
What are implicit objects in JSP

Jsp implicit objects

In JSP implicit objects are the objects created by implicitly, and can be directly used in Jsp programs with out declaring them. This is basically to reduce the code written by developer.

Below is list of Jsp implicit objects, along with the details

Implicit Object name Instance of class Brief
request javax.servlet.http.HttpServletRequest Used to retrieve all request parameters submitted from HTML page and to retrieve Cookies on Browser.

response

javax.servlet.http.HttpServletRespone used to send response from servlet to HTML Page, add Cookies to Browser, in Request Dispatcher

out

java.io.PrintWriter Used to send output from Servlet to Browser, generally HTML code

session

javax.servlet.http.HttpSession Stores details of current session in progress, using this session attributes can be set and get.

config

javax.servlet.ServletConfig used to retrieve initialization parameters which are specific to each servlet

application

javax.servlet.ServletContext used to retrieve initialization parameters which are common to all servlets

exception

java.lang.Throwable Has details of exception being thrown from a Jsp page.

pageContext

javax.servlet.jsp.PageContext Using this object you can find attribute, get attribute, set attribute and remove attribute at any of levels JSP Page (PAGE_CONTEXT) or HTTP Request (REQUEST_CONTEXT) or HTTP Session (SESSION_CONTEXT) or Application Level ( APPLICATION_CONTEXT)

page

java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.