Session Tracking Using Servlet

A session is a collection of HTTP request , over a period of time. A session is specific to the user and for each user a new session is created to track all the request from the user. In servlet session tracking can used to track the user state. Session tracking is also known as session handling, it is a mechanism used to maintain the state of a user within a series of requests across some period. We can say that session tracking is a means to keep track of session data. This data represents the data being transferred in a session.

Types Of Session Tracking

There are four types of session tracking they are as follows

  • URL rewriting
  • Cookies
  • Hidden from fields
  • HTTP session

URL Rewriting

With URL rewriting every local URL the user might click on, we can pass extra information. This extra information can be written in the form of added parameters, extra path or some specific change in the URL. As a limited space is available in rewriting the URL , the extra information is limited to a unique session ID. With this mechanism, you can append a client’s session data to the request path as a query string or as a part of path info.

Using Query String For URL Rewriting:

A query string is a string appended after the requested uniform resource identifier(URI), with the ‘?’ character as a separator. The requested URL is context path plus Servlet path plus path info.
Query string is divided into different parameters, separated by the & character.
Consider the following url :
http:/localhost: 8080/javabeat/login?uname=abc&pass=xyz
In the preceding url,

  1. /javabeat/login is the request url and
  2. uname=abc&pass=xyz is a query string.

Using path Info for URL Rewriting:
Path info is a part of the request URL, which is not a part of context path or Servlet path.
consider the following URL:
http:/localhost: 8080/javabeat/login?uname=abc&pass=xyz
In the preceding URL,

    • /login;uname=abc&pass=xyz is path info

.

Advantages of URL Rewriting:

  1. When we need to maintain a small amount of data for a shot period of time such as between two or three consecutive request.
  2. When we need to navigate a specific data we can use the query string.
  3. Extra form submission is not required on each pages.

Disadvantages of URL Rewriting:

  1. URL Rewriting can send only textual information
  2. URL Rewriting works only on links.

Hidden Form Fields

Hidden form field is a type of HTML form field, but remains hidden in the view. Hidden form is a form of session tracking which saves the information in client browser itself. In this mechanism invisible text field is used to maintain the state of an user.

The following is the syntax for using a hidden form field:

<input type=”hidden” name=”uname” value=”user1”/>

Advantages and Disadvantages of Hidden Form Field:

  1. Hidden form field mechanism is similar to the URL rewriting mechanism, but works even with the HTTP POST method. This mechanism is not restricted to the GET method only, we can also use the POST method without using path info.
  2. Hidden form field mechanism also has some disadvantages For example it only works when every page is dynamically generated by a form submission.

Cookies

A cookie is a file containing the information that is sent by a Web server to a client. Cookies transmitted through the HTTP to client .Cookies are saved at the client side for the given domain and path. The cookies file persist on the client machine and the client browser returns cookies to the original server. The servlet API provides a class named cookie under the javax.servlet.http package. javax.servlet.http cookie object is designed to represent a HTTP cookie, which provides a convenient way to exchange data of a cookie between container and servlet. The javax.servlet.http.cookie class consist of one constructor with two String arguments. The first argument take cookie name and second take cookie value.

Various methods in the javax.servlet.http.cookie class are as follows:

  1. setValue (String)- This can sets the value of cookie. The value should not contain white space , brackets, parentheses, equal to sign, commas, double quotes, slashes, question mark, at sign, colon, or semicolon.
  2. getValue ()- This returns the value of cookie.
  3. getName()- This returns the name of cookie.
  4. setComment(string)- This can sets the comment to cookie.
  5. getComment()- This returns the comment that describes the purpose of a cookie, or null if there are no comments associated with cookie.
  6. setVersion(String), getVersion()- Set and get the version of a cookie, respectively.
  7. setDomain(String), getDomain()- Set and get the domain, respectively, with which cookie is associated.
  8. setPath(String), getPath()- Set or get the path of the location, respectively, where the client should return a cookie.
  9. setSecure(Boolean), getSecure(Boolean)- Set or get the secure flag of a cookie, respectively. Setting secure attribute to true indicates that the cookie should only be sent by using a secure protocol, such as HTTP or SSL.

Advantages of Cookies:

  1. Cookies reduce network traffic, compared to URL rewriting.
  2. Cookies maintain client data.
  3. Cookies help reduce the complexity of a application logic

Disadvantages of Cookies:

  1. Cookies are not secure, they can be viewed and modified and so personal information can be expressed.
  2. Cookies are HTTP specific and so can be used for HTTP request only.
  3. Cookies size allocated for a client is limited and varies from one client application to another.

HTTP Session

In this Mechanism the web container maintains the users data and tracks the users session by using URL rewriting or cookies. This mechanism helps to maintain a unique identity for each of session without using URL rewriting or cookies.

HTTP session in servlet involves the following task:

  1. Storing information in session
  2. Looking up information in a session.
  3. Attaching the session identity to the URLs
  4. Creating a new session object when necessary

Locating a session object:

There are two methods of locating session they are as follows

getSession() and getSession(Boolean)

getSession(): This method is called when a servlet needs to locate a session associated with the current request. This session in turn is used to retrieve or store data.
The getSession() method is used to create or locate a session. This method performs following operation:

  1. Finds whether or not the current request holds the session id in cookies or request the URLspath info.
  2. Returns the null value, if false Boolean argument is passed through the getSession method.

getSession(Boolean):

When we want to create and associate a new session with a client, we call the getSession() or getSession(Boolean) method.

Example of session Tracking:

package javabeat.net.servlets;

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 SessionTrackingExample extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {

		response.setContentType("text/html");

		HttpSession session = request.getSession();

		String heading;

		Integer accessCount =

		(Integer) session.getAttribute("accessCount");

		if (accessCount == null) {

			accessCount = new Integer(0);

			heading = "Welcome To Javabeat";

		} else {

			heading = "Welcome Back";

			accessCount = new Integer(accessCount.intValue() + 1);
		}

		session.setAttribute("accessCount", accessCount);

		PrintWriter out = response.getWriter();

		String title = "Session Tracking Example";

		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +

		"Transitional//EN\">\n";

		out.println(docType +

		"<HTML>\n" +

		"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +

		"<BODY BGCOLOR=\"#FDF5E6\">\n" +

		"<CENTER>\n" +

		"<H1>" + heading + "</H1>\n" +

		"<H2>Information on Your Session:</H2>\n" +

		"<TABLE BORDER=1>\n" +

		"<TR BGCOLOR=\"#FFAD00\">\n" +

		" <TH>Info of Session<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>Number of Previous Accesses\n" +

		" <TD>" + accessCount + "\n" +

		"</TABLE>\n" +

		"</CENTER></BODY></HTML>");
	}
}

Output:

Execute the above example in Eclipse, we get the following output:
servlet_sessiontrack_demo

Previous Tutorial : Request Headers In Servlet  || Next Tutorial : Servlet Filter

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*