Role Of Session Management In Java

Session Management in Java

session management in java

This article is aimed to explain about session management in servlets using different techniques and with example programs.

What is a Session?

  • A session is a period of time where the user sends multiple requests and receives multiple responses.
  • If you are developing any web application then a client may send multiple requests with some information.
  • The information sent by the client with one request will not be accessed in another request.
  • Session means the duration when the client is accessing the application first time and when the client is leaving the application.
  • If you want to access the data of one request into another request then you need to manage the SESSION.
  • If you want to manage the SESSION in the WEB application, you have to do two things.
    • Identify the client
    • Manage the conversational state(Storing the client-specific information).
  • To identify the client as new or old, the container will use Session id.
  • To store clients conversational state or data. You have to use the HttpSession object.

HttpSession object will be created by the container when you call getSession() method the first time.
HttpSession session = request.getSession();

How Session works:

session management

The basic concept of session, whenever a user starts using your application, we can save unique identification information about that, in an object until it destroyed. So wherever the user goes, we will always have his information and we can always manage which user is doing what. Whenever a user wants to exit from your application, destroy the object with his information.

Implementation inside the getSession() method:

class HttpServletRequestImpl implements HttpServletRequest
public HttpSession getSession()

  • checks whether the incoming request contains the cookie with name JSESSIONID or not.
  • If the incoming request contains the Cookie with name JSESSIONID then collects the value of the cookie which is Session id and picks the session object related to session id.
  • If the incoming request does not contain the cookie with name JSESSIONID then following steps with happen:-
    1. create a session object. HttpSession session= request.getSession();
    2. Generates a unique session id. String id= <Hexadecimal_OF_ClientIPADD>+<Hexadecimal_OF_CurrentTimeStamp>+<Hexadecimal_OF_ServletTimeStamp>;
    3. stores the session id in session object. Session.setId(id);
    4. create the cookie with the name JSESSIONIDCookies c = new Cookies(“JSESSIONID”, id);
    5. Adds the cookie to the response object.Res.addCookie(c);
  • Returns the Session object


There are 4 session management techniques and they are listed below:

  1. HttpSession
  2. Cookies
  3. Url-Rewriting
  4. Hidden Fields

You can use the following to store the client’s conversational data.

  1. HttpSession
  2. Cookies

You can use the following to carry the Session-Id.

  1. Cookies
  2. Url-Rewriting
  3. Hidden fields

Exploring HttpSession

  1. HttpSession is an interface available in a Javax.servlet.HTTP package
  2. you can get the HttpSession object with the following methods of HttpservletRequest.
  • HttpSession getsession();
  • HttpSession getSession(boolean)

If the boolean value is true:-

HttpSession s =req.getSession(true); then following things will happen.

if(session object available) then
return that
create a new session object and return

If the boolean value is false as:-
HttpSession s = req.getSession(false); then following thing will happen:

if(session object available) then
return that
return null

You can store and access the user-specific data in HttpSession object as an attribute with the following methods:

  1. void setAttribute(String Object)
  2. Object getAttribute(String)
  3. void removeAttributes(String)
  4. Enumeration getAttributeNames()

You can also use the following 4 methods that are deprecated.

  1. Void putvalue(String, Object)
  2. Object getValue(String)
  3. void removeValue(String)
  4. String[] getValueNames()

You can destroy the HttpSession object by calling invalidate() method:

Q1. How can i check whether session object returned by getSession() is old or new?
Ans: Using boolean is new() method.

Q2. How can I get the session associated with the session object?
Ans: using getId() method.

Q3. How can I get the session creation time?
Ans: using getCreationTime() method.

Q4. How can I find the Session available?
Ans: using getSession(false);
By calculating the time difference between session creation time and a current time.

Q5. How can I access when the session was accessed last time?
Ans: using getLastAccessedTime();

Q6. How can I specify the idle timeout (or) inactive interval?
Ans: you can specify the idle timeout in two ways:

  1. setMaxInactiveInterval(int) in terms of seconds
  2. specify the following tags in web.xml<session-config><session-timeout>5</session-timeout><session-config>// interms of min

Q7. Can i access the Servletcontext with session.
Ans: Yes, you can with the following method: ServletContext getServletContext();

  1. A session will be created newly when you call getSession() method the first time.
  2. In every JSP, by default getSession() will be called. ie. When you request for any JSP then session object will be created automatically without your calling the getSession() method.
  3. If you want you can disable the automatic session creation by specifying the following tag:
    <%@ page session=”false” %>
Exploring Cookies:
  1. Cookies is a class available in a javax.servlet.HTTP package.
  2. Cookies are simple information with name and value.
  3. Normally cookie’s will be created at server machine and persist at a client machine.
  4. Cookies created at server machine will come to the client machine and persist at the client machine,
  5. Cookies persistent at client machine will go to server machine along with HttpRequested.
Exploring Cookies Explanation:-
  1. Creating cookies: Cookies ck= new Cookies(“email”, [email protected]);
  2. Adding cookies to response: response.addCookie(ck);
  3. Accessing cookies from request:
    Cookies ck[] = request.getCookies();for(Cookies c:ck);String cn= c.getName();String cv= c.getValue();System.out.println(“cn+ “ ”+ cv);}

Q) How can i specify the expiry time for cookies?
Ans: using setMaxAge() method;

URL-Rewriting and Hidden Fields
  1. The container uses Session id to identify the client as old or new.
  2. Container send the session id to the client machine with the cookies with name JSESSIONID
  3. Sometimes, you may get problems with cookies.
  • When your browser is not supporting the cookies.
  • When the client deletes the cookies.
  • When any problem happens to cookies then request will not carry the cookie with name JSESSIONID
  • if a request is coming without JSESSIONID cookies then the container will treat that client as new and provides the new session object and new session id i.e, Client is losing the previous session,

Object and conversational data available in that session object.
You can use URL-Rewriting or hidden fields to carry the session id from client to server and from server to client.

  1. URL_Rewritng is the process of attaching the session id to the URL. It is also called the encoding the URL.
  2. To encode the URL, use the following.
    1. response.encodeURL(“…..”);
    2. response.encodeURL(“ …”);
  3. encodeUrl() method takes the URL as a parameter and it will generate the following URL after encoding.;JSESSIONID=A12jkd6d57s
Hidden fields.
    1. You can store the session id in the hidden fields as follows.<input type=”hidden” name=”JSESSIONID” value=”<%=session.getId()%>”
    2. when you are developing any web application using Struts, JSP, Spring MVC frameworks then you no need to implement URL-Rewriting concept. These frameworks have inbuilt support for it.

The use of session management is an important design issue because of the complexity of today’s Web sites. As Java developers, we have access to a powerful and robust session manager through the use of the HttpSession API. Learning all of Java’s session management features will make your job as a Web developer easier and help you create a better experience for your Web site visitors. That’s all for session management in java servlets, we will look into Servlet Filters and Listeners in future articles. Please, feel free to drop a comment in the below comment box, if you find any doubt in the topic or you want to share more information about the topic. Happy Learning!

READ NOW :- Some Unknown Facts About Java Servlet Filter

Leave a Reply

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