Session Management and Cookies in JAVA

Introduction

 
This article is the next in a series of articles about Java Servlets. In this article, we will learn about maintaining the client state and Session in Servlet.
Many applications require a series of requests from a client to be associated with one another. The shopping cart software is a classic example; a client can select the items from multiple actions in his virtual box. Other examples include sites that use online communication portals, or database managing. Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.
 
Since the HTTP protocol is stateless. This protocol covers only a single request (with the connection initiated by the user agent) and a response. This has the following ramifications:
  1. The protocol has no mechanism by which a series of unique requests from a user agent may be identified as being from the same user agent. Consequently, in a transaction spanning multiple requests and responses, the webserver can not uniquely determine that all the requests are from the same user agent. A user, therefore, can not establish a dialogue with the webserver to perform a business transaction.
  2. Since connections are not maintained by either of the transacting parties, the state of the transaction (and the application) can not be preserved across multiple requests.

Session: 

 
A session is defined as a series of related browser requests that come from the same client during a certain time period. Session tracking ties together a series of browser requests—think of these requests as pages—that may have some meaning as a whole, such as a shopping cart application. In computer language login to logout, the duration is called the session. 
 

How to Access a Session?

 
We can access the session object from the Java servlet API, that provides the HttpSession interface for session tracking and state management. this session is created by calling the getSession() method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one.
 
For Example:
  1. HttpSession session=request.getSession();            
Mostly when we use login page then use getSession() if we use another page instead of login then we use getSession(boolean). Through this method, we request for a session and the container will create or use the session and take care of generating the session id, creating a new cookie and setting the cookie as a part of the response. Everything is done by a container.
 
A number of methods are defined in the Java Servlet specification. (A complete API can be found on http://java.sun.com.) The methods you'll use most often and the ones we'll focus on are: 
  1. setAttribute(String name, Object value)
    Binds an object to this session using the name specified. Returns nothing (void). 
  2. getAttribute(String name)
    Returns the object bound with the specified name in this session, or null if no object is bound under this name.
  3. removeAttribute(String name)
    Removes the object bound with the specified name from this session. Returns nothing (void).
  4. invalidate() 
    Invalidates this session and unbinds any objects bound to it. Returns nothing (void).
  5. isNew() 
    Returns a Boolean with a value of true if the client does not yet know about the session or if the client chooses not to join the session.
There are four approaches for session Tracking
  1. Cookie
  2. Url Rewriting
  3. Hidden form field
  4. Http Session API
Here we discuss only Cookie and URL Rewriting.
  1. Cookie: A text file or a message created by a web server and stored at a web browser or client location. The message is then sent back to the server each time the browser requests a page from the server. The main purpose of cookies is to identify the client and possibly prepare customized Web pages for them. Mostly Session Cookies and persistent cookie are used.
  2. Session cookie: The session cookie is stored in temporary memory and is not retained after the browser is closed. Session cookies do not collect information from the user computer. They typically will store information in the form of a session identification that does not personally identify the user. A session cookie is also called a transient cookie.
  3. Persistent cookie: A persistent cookie will outlast user sessions. A cookie that is stored on a user's hard drive until it expires (persistent cookies are set with expiration dates) or until the user deletes the cookie. persistent cookies are also called tracking cookies or in-memory cookies.
  4. We make an application that generates a Web page showing some information about the current session by using javax.servlet.http.HttpSession interfac. In this application first, we create a HttpSession object and use some methods. In this application, we make a servlet(CookieServ.java) and an XML file. In this servlet we use
CookieServ.java: 
  1. import java.io.IOException;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.util.Date;  
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import javax.servlet.http.HttpSession;  
  10.   
  11. public class CookieServ extends HttpServlet  
  12. {  
  13.  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  14.  {  
  15.   HttpSession session = request.getSession();  
  16.   response.setContentType("text/html");  
  17.   PrintWriter pw = response.getWriter();  
  18.   String str;  
  19.   Integer Count = new Integer(0);;  
  20.   if (session.isNew())  
  21.   {  
  22.    str = "Welcome, Newcomer";  
  23.   }   
  24.   else  
  25.   {  
  26.    str = "Welcome Back";  
  27.    Integer oldCount = (Integer) session.getAttribute("Count");  
  28.    if (oldCount != null)  
  29.    {  
  30.     Count = new Integer(oldCount.intValue() + 1);  
  31.    }  
  32.   }  
  33.   pw.println("<BODY BGCOLOR=\"pink\">\n" +  
  34.    "<H1 ALIGN=\"CENTER\">" + str + "</H1>\n" +  
  35.    "<H2>Information about Your Session:</H2>\n" +  
  36.    "<TABLE BORDER=1 ALIGN=CENTER>\n" +  
  37.    "<TR BGCOLOR=\"yellow\">\n" +  
  38.    "  <TH>Info Type<TH>Value\n" +  
  39.    "<TR>\n" +  
  40.    "  <TD>Session ID\n" +  
  41.    "  <TD>" + session.getId() + "\n" +  
  42.    "<TR>\n" +  
  43.    "  <TD>Creation Time\n" +  
  44.    "  <TD>" + new Date(session.getCreationTime()) + "\n" +  
  45.    "<TR>\n" +  
  46.    "  <TD>Time of Last Access\n" +  
  47.    "  <TD>" + new Date(session.getLastAccessedTime()) + "\n" +  
  48.    "<TR>\n" +  
  49.    "  <TD>Time out\n" +  
  50.    "  <TD>" + new Date(session.getMaxInactiveInterval()) + "\n" +  
  51.    "<TR>\n" +  
  52.    "  <TD>Number of Previous Accesses\n" +  
  53.    "  <TD>" + Count + "\n" +  
  54.    "</TABLE>\n" +  
  55.    "</BODY></HTML>");  
  56.  }  
  57.  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  58.  {  
  59.   doGet(request, response);  
  60.  }  
  61. }  
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.    
  3. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"  
  4.   
  5. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  6.    
  7. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd%22%20id=%22WebApp_ID%22%20version=%222.5 id="WebApp_ID" version="2.5">  
  8.    
  9.  <servlet>   
  10.     <servlet-name>CookieServ</servlet-name>   
  11.     <servlet-class>CookieServ</servlet-class>   
  12.   </servlet>  
  13.    
  14.   <servlet-mapping>   
  15.     <servlet-name>CookieServ</servlet-name>   
  16.     <url-pattern>/CookieServ</url-pattern>   
  17.   </servlet-mapping>  
  18.    
  19. </web-app>   
When we run this application on Server the output of this application is given below:
CookieNewcomer.gif
 
If we refresh this page then the output is given below:
 
cookieOld.gif
  
I think this article will be helpful to learn about Session management in J2EE.