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 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 web server can not uniquely determine that all the requests are from the same user agent. A user, therefore, can not establish a dialog with the web server 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 duration is called the session. 

How to Access a Session

We can access the session object from 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:

              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 response. Everything is done by 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: 
setAttribute(String name, Object value): Binds an object to this session using the name specified. Returns nothing (void). 

getAttribute(String name): Returns the object bound with the specified name in this session, or null if no object is bound under this name.

removeAttribute(String name): Removes the object bound with the specified name from this session. Returns nothing (void).


invalidate(): Invalidates this session and unbinds any objects bound to it. Returns nothing (void).


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.

Cookie: A text file or a message created by web server and stored at 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 client and possibly prepare customized Web pages for them. Mostly Session Cookies and persistent cookie are used.

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. Session cookie is also called transient cookie.

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.

We make a 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 a xml file.In this servlet we use

CookieServ.java: 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CookieServ extends HttpServlet
{
      
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
      {
            HttpSession session=request.getSession();
            response.setContentType(
"text/html");
            PrintWriter pw=response.getWriter();
          String str;
          Integer Count = 
new Integer(0);;
          
if (session.isNew())
          {
            str = 
"Welcome, Newcomer";
          } 
          
else 
          {
            str= 
"Welcome Back";
            Integer oldCount =(Integer)session.getAttribute(
"Count"); 
            
if (oldCount != null) 
            {
              Count =
new Integer(oldCount.intValue() + 1);
            }
          } 
          pw.println(
"<BODY BGCOLOR=\"pink\">\n" +
                
"<H1 ALIGN=\"CENTER\">" + str + "</H1>\n" +
                
"<H2>Information about Your Session:</H2>\n" +
                
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
                
"<TR BGCOLOR=\"yellow\">\n" +
                
"  <TH>Info Type<TH>Value\n" +
                
"<TR>\n" +
                
"  <TD>Session ID\n" +
                
"  <TD>" + session.getId() + "\n" +
                
"<TR>\n" +
                
"  <TD>Creation Time\n" +
                
"  <TD>" + new Date(session.getCreationTime()) + "\n" +
                
"<TR>\n" +
                
"  <TD>Time of Last Access\n" +
                
"  <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
                
"<TR>\n" +
                
"  <TD>Time out\n" +
                
"  <TD>" + new Date(session.getMaxInactiveInterval()) + "\n" +
                
"<TR>\n" +
                
"  <TD>Number of Previous Accesses\n" +
                
"  <TD>" + Count + "\n" +
                
"</TABLE>\n" +
                
"</BODY></HTML>");
      }
      
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
      {
            doGet(request, response);
      }
}

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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
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">
 <servlet>
    <servlet-name>CookieServ</servlet-name>
    <servlet-class>CookieServ</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CookieServ</servlet-name>
    <url-pattern>/CookieServ</url-pattern>
  </servlet-mapping>
</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 bellow:

cookieOld.gif

I think this article will be helpful to learn about Session management in J2EE.

Up Next
    Ebook Download
    View all
    Learn
    View all