State management using HttpSession

In this post, you will learn:

  • What is a HttpSession?
  • How to manage client’s state using HttpSession?
  • Differences between HttpSession and other methods?

what is a HttpSession?

HttpSession is an interface of servlet API. Its implementation is provided by server vendors. An object of type HttpSession can be get created for each user in a Java web application. This object can be used to store client’s state between requests.

Differences between HttpSession object and other methods of state management

1. In case of HttpSession, client’s state is stored on the server where as in other methods(Cookies, Hidden Form Fields & URL rewriting) it is sent to the client and again received back on the server in one form or another.

2. In case of HttpSession, textual information as well as objects and collections can be persisted between requests. In other methods only textual information can be persisted.

3. HttpSession requires heap memory on the server in proportion to the no. of users for creating objects, other methods don’t.

Obtaining a HttpSession ojbect for the current user:

HttpSession object for the current user can be obtained using the getSession() method of HttpServletRequest interface. This method has following syntax:

1. public HttpSession getSession();

2. public HttpSession getSession(boolean createFlag);

Both these methods check whether a HttpSession object exists for the current user or not. If exists, its reference is returned otherwise a HttpSession object is created for the current user and its reference returned by the first method. The second method creates HttpSession object only if the value of createFlag is true. If createFlag is false and no HttpSession object exists for the current user, null is returned by it.

Commonly used methods of HttpSession:

1. setAttribute(): This method is used to store an attribute in the session scope.

public void setAttribute(String name, Object value) throws IllegalStateException;

2. getAttribute(): This method is used to obtain the value of an attribute from the session scope.

public Object getAttribute(String name) throws IllegalStateException;

3. getAttributeNames(): This method is used to obtain the name of all session scope attributes.

public Enumeration getAttributeNames() throws IllegalStateException;

4. removeAttribute(): This method is used to remove an attribute from the session scope.

public void removeAttribute(String name) throws IllegalStateException;

5. setMaxInactiveInterval(): This method is used to specify the time in seconds for which the session object is maintained on the server even if no request is received from the client.

public void setMaxInactiveInterval(int seconds) throws IllegalStateException;

5. invalidate(): This method is used to free the current session.

public void invalidate() throws IllegalStateException;

InvalidStateException which is listed with all the methods, is thrown by them when they are invoked on an invalidated object.

Practical example of state management using cookie:

Same application that we have used in the Cookie and hidden form fields, is modified to test the state management using HttpSession.

First, the index.html :

<form action="welcomeServlet" method="post">Name <input name="name" type="text" />
<input type="submit" value="submit" /></form>

Second the WelcomeServlet. It stores the user name as attribute in the session scope so that can be made available to the TourServlet in the next request.

package com.techmentro.learningpad;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet 
{
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		//Value of name request parameter is read
		String user=request.getParameter("name");
		//HttpSession object is get created for the user
		HttpSession session=request.getSession();
		//user name is stored as attribute in the session scope.
		session.setAttribute("userName",user);
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("Welcome, "+user);
		//A hyper link  is added to send the request to the tourServlet
		out.println("
 Take a Tour");
		out.close();
	}
}

Third, the TourServlet. It reads the user name from the session and invalidates the session.

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class TourServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		//HttpSession object is get created for the user
				
				//HttpSession object is obtained for the user
				HttpSession session=request.getSession();
				//value of userName attribute is fetched from the session scope.
				String user=(String)session.getAttribute("userName");
				//session is invalidated as it will not be required after this request
				session.invalidate();
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("Sorry, "+user);
		out.println("
 Site is down for routine maintenance. Visit again later.");
		out.close();
	}
}

Fourth, the web.xml.

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
 <servlet>
 <servlet-name>s1</servlet-name>
 <servlet-class>com.techmentro.learningpad.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s1</servlet-name>
 <url-pattern>/welcomeServlet</url-pattern>
 </servlet-mapping>
 <servlet>
 <servlet-name>s2</servlet-name>
 <servlet-class>com.techmentro.learningpad.TourServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s2</servlet-name>
 <url-pattern>/tourServlet</url-pattern>
 </servlet-mapping>
</web-app>

Output screen images of the practical example:

The first screen represents the home page generated by index.html. Two different browsers are used to represent two different users as before.

session_screen1

The second screen represents the response of the WelcomeServlet.

session_screen2

The third screen represents the response of the TourServlet. The user name displayed in this response page is obtained as from the session attribute.

session_screen3
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

One thought on “State management using HttpSession

  1. Nice Content!
    It is very helpful and authentic content on Java and the best one I ever found online on Java technology.Every one should read this nice and quality based content.

    Best of luck for your work!

Leave a Reply

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