Bitcoin

Bitcoin
Bitcoin

Servlet Session Tracking

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server −

Cookies

A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID as follows −

This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular () hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.

URL Rewriting

You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and it works even when browsers don't support cookies. The drawback of URL re-writing is that you would have to generate every URL dynamically to assign a session ID, even in case of a simple static HTML page.

The HttpSession Object

Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession()of HttpServletRequest, as below −
HttpSession session = request.getSession();
You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object −
Sr. No.Method & Description
1
public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
2
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
3
public long getCreationTime()
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
4
public String getId()
This method returns a string containing the unique identifier assigned to this session.
5
public long getLastAccessedTime()
This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT
6
public int getMaxInactiveInterval()
This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses.
7
public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
8
public boolean isNew(
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
9
public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
10
public void setAttribute(String name, Object value)
This method binds an object to this session, using the name specified.
11
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Session Tracking Example

This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
         
      // Create a session object if it is already not  created.
      HttpSession session = request.getSession(true);
         
      // Get session creation time.
      Date createTime = new Date(session.getCreationTime());
         
      // Get last access time of this web page.
      Date lastAccessTime = new Date(session.getLastAccessedTime());

      String title = "Welcome Back to my website";
      Integer visitCount = new Integer(0);
      String visitCountKey = new String("visitCount");
      String userIDKey = new String("userID");
      String userID = new String("ABCD");

      // Check if this is new comer on your web page.
      if (session.isNew()) {
         title = "Welcome to my website";
         session.setAttribute(userIDKey, userID);
      } else {
         visitCount = (Integer)session.getAttribute(visitCountKey);
         visitCount = visitCount + 1;
         userID = (String)session.getAttribute(userIDKey);
      }
      session.setAttribute(visitCountKey,  visitCount);

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      String docType =
         " +
         "transitional//en\">\n";

      out.println(docType +
         "\n" +
            ""</span><span class="pln" style="box-sizing: border-box;"> </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> title </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> </span><span class="str" style="box-sizing: border-box; color: rgb(0, 136, 0);">"\n" +
            
            "\n" +
               "

"

+ title + "
\n" + "

Session Information

\n" + "\n"
+ " \n" + "Session info value\n" + " \n" + "id \n" + ""+ session.getId() + " \n" + " \n" + "Creation Time \n" + ""+ createTime + \n" + " \n" + "Time of Last Access \n" + ""+ lastAccessTime + \n" + " \n" + "User ID \n" + ""+ userID + \n" + " \n" + "Number of visits \n" + ""+ visitCount + " \n" + "\n" + " " ); } }


Compile the above servlet SessionTrack and create appropriate entry in web.xml file. Now running http://localhost:8080/SessionTrack would display the following result when you would run for the first time −

Welcome to my website

Session Infomation

Session infovalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits0
Now try to run the same servlet for second time, it would display following result.

Welcome Back to my website

Session Information

info typevalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits1

Deleting Session Data

When you are done with a user's session data, you have several options −
  • Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key.
  • Delete the whole session − You can call public void invalidate()method to discard an entire session.
  • Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
  • Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
  • web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.

   15

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.

Servlet Cookies Handling

Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; 
   path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz
A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects.

Servlet Cookies Methods

Following is the list of useful methods which you can use while manipulating cookies in servlet.
Sr.No.Method & Description
1
public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.
2
public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.
3
public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4
public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5
public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.
6
public void setValue(String newValue)
This method sets the value associated with the cookie
7
public String getValue()
This method gets the value associated with the cookie.
8
public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9
public String getPath()
This method gets the path to which this cookie applies.
10
public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11
public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12
public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Setting Cookies with Servlet

Setting cookies with servlet involves three steps −
(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the following characters −
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24); 
(3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows −
response.addCookie(cookie);

Example

Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class HelloForm extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Create cookies for first and last names.      
      Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

      // Set expiry date after 24 Hrs for both the cookies.
      firstName.setMaxAge(60*60*24);
      lastName.setMaxAge(60*60*24);

      // Add both the cookies in the response header.
      response.addCookie( firstName );
      response.addCookie( lastName );

      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Setting Cookies Example";
      String docType =
         " + "transitional//en\">\n";
      
      out.println(docType +
         "\n" +
            "
               "</span><span class="pln" style="box-sizing: border-box;"> </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> title </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> </span><span class="str" style="box-sizing: border-box; color: rgb(0, 136, 0);">"
            \n" +
            
            "\n" +
               "

"

+ title + "
\n" + "
    \n"
+ "
  • First Name: "
  • + request.getParameter("first_name") + "\n" + "
  • Last Name: "
  • + request.getParameter("last_name") + "\n" + "\n" + " " ); } }


    Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet.
     
    
       
          
    action = "HelloForm" method = "GET"> First Name: type = "text" name = "first_name"> /> Last Name: type = "text" name = "last_name" /> type = "submit" value = "Submit" />
    Keep above HTML content in a file Hello.htm and put it in /webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
    First Name: 
    Last Name:  
    Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.
    Next section would explain you how you would access these cookies back in your web application.

    Reading Cookies with Servlet

    To read cookies, you need to create an array of javax.servlet.http.Cookieobjects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

    Example

    Let us read cookies which we have set in previous example −
    // Import required java libraries
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
    // Extend HttpServlet class
    public class ReadCookies extends HttpServlet {
     
       public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          
          Cookie cookie = null;
          Cookie[] cookies = null;
    
          // Get an array of Cookies associated with this domain
          cookies = request.getCookies();
    
          // Set response content type
          response.setContentType("text/html");
    
          PrintWriter out = response.getWriter();
          String title = "Reading Cookies Example";
          String docType =
             " +
             "transitional//en\">\n";
             
          out.println(docType +
             "\n" +
             ""</span><span class="pln" style="box-sizing: border-box;"> </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> title </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> </span><span class="str" style="box-sizing: border-box; color: rgb(0, 136, 0);">"\n" +
             "\n" );
    
          if( cookies != null ) {
             out.println("

    Found Cookies Name and Value

    "
    ); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( ) + " "); } } else { out.println("

    No cookies founds

    "
    ); } out.println("
    "); out.println(""); } }
    Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookies would display the following result −

    Found Cookies Name and Value

    Name : first_name, Value: John Name : last_name, Value: Player

    Delete Cookies with Servlet

    To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps −
    • Read an already existing cookie and store it in Cookie object.
    • Set cookie age as zero using setMaxAge() method to delete an existing cookie
    • Add this cookie back into response header.

    Example

    The following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name.
    // Import required java libraries
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
    // Extend HttpServlet class
    public class DeleteCookies extends HttpServlet {
     
       public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          
          Cookie cookie = null;
          Cookie[] cookies = null;
             
          // Get an array of Cookies associated with this domain
          cookies = request.getCookies();
    
          // Set response content type
          response.setContentType("text/html");
     
          PrintWriter out = response.getWriter();
          String title = "Delete Cookies Example";
          String docType =
             " + "transitional//en\">\n";
             
          out.println(docType +
             "\n" +
             ""</span><span class="pln" style="box-sizing: border-box;"> </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> title </span><span class="pun" style="box-sizing: border-box; color: rgb(102, 102, 0);">+</span><span class="pln" style="box-sizing: border-box;"> </span><span class="str" style="box-sizing: border-box; color: rgb(0, 136, 0);">"\n" +
             "\n" );
             
          if( cookies != null ) {
             out.println("

    Cookies Name and Value

    "
    ); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ) { cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : " + cookie.getName( ) + " "); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" "); } } else { out.println("

    No cookies founds

    "
    ); } out.println("
    "); out.println(""); } }
    Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result −

    Cookies Name and Value

    Deleted cookie : first_name
    Name : first_name, Value: John
    Name : last_name, Value: Player
    Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows −

    Found Cookies Name and Value

    Name : last_name, Value: Player
    You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.

    Facebook