How track session Java Example

Session Tracking Java Web Application

What is session: Session is communication between client and the server. HTTP (Hypertext Transfer Protocol) function as request response protocol in client server communication model. HTTP is stateless protocol so when client sends request to the server there won’t be any track of request, http protocol only pass request to the server and forget it.

HTTPSession provides way to identify user when he sends more than one request while visit the web site. It store information about the user who visited the site.

Why its important to maintain the session: When user visit the web site and send continuous request to the server, server can not identify who is the client sending the request as HTTP is stateless protocol. Based on the scenario and web site content if conversational state needs to be maintained then we should utilized session tracking technique. For example: If you are visiting on Amazon web site to do your shopping for multiple items then amazon should keep maintaining your state until you are finished with it and finally checkout your shopping cart for payment and shipment.

Session tracking techniques:

  • Hidden form fields
  • URL rewriting
  • User authorization
  • Cookies
  • Session tracking API

Apart from Session tracking API all others are traditional session tracking technologies which is widely used in all server side technology in different languages. Session tracking API provide by the java servlet which is build on top other four above traditional session tracking technologies mean it has all four functionality avaible.

  • Hidden form fields: It’s one way to support anonymous session tracking is to utilize hidden form fields. As name says these fields added to the HTML form that will not displayed in client browser. These fields are sent back to the server when form that contains this fields is submitted. In below example you could include hidden form fields in HTML:
<FORM ACTION="/servlet/javahonk" METHOD="POST">
...
<INPUT TYPE=hidden NAME="java" VALUE="honk">
<INPUT TYPE=hidden NAME="location" VALUE="ny">
...
</FORM>

It’s only technique to hide fields from the user page otherwise it’s define constant variables to the form. When servlet receiving the submitted form there is no difference between hidden field and visible fields.

  • URL rewriting: URL rewriting is anonymous way to support session tracking. Using URL rewriting every local URL from the client machine is dynamically modified or rewritten to append extra information into it. Those extra information will be in the form of extra path information as added parameters OR some custom server specific URL changes. Because of the limited space available in rewriting to the URL extra information is usually limited to unique session ID. For example:

         http://techiworks.com/servlet/test — Original URL
         http://techiworks.com/servlet/test?sessionid=akdjf1425666 — Rewritten URL

URL rewriting technique has its own advantages and disadvantages. Utilize extra path information works on all servers, it also works as target for the forms that uses both GET and POST methods. It do not work well if the servlet has to use extra path information as true path information although using added parameter works on all servers but it fails as target for forms that use POST method, it can cause parameter naming collisions. While using custom server specific changes works under all scenario for servers that support change. On other side it do not work at all for servers that don’t support change.

  • User authorization: Basic purpose of user authorization is to authenticate the user to use the web application and give the authorization. There are many different ways are available to authorize the user.
    • HTTP Basic Authentication
    • Form-Based Authentication
    • HTTPS Client Authentication
    • Digest Authentication

Based on above chosen authentication type user can be identified and session can be maintained

  • Cookies: Session maintain through cookies is another way to maintain session between client and server. Cookies is name value pair object where small amount of information sent by the servlet to the web browser and this information saved by the browser and later sent back to the server. Cookies value could be uniquely identify the client so its commonly used for session tracking. Cookies has name and single value and it can also include optional attributes such as comment, path and domain qualifiers, maximum age, version number.

Servlet sends cookies to browser using HttpServletResponse.addCookie(javax.servlet.http.Cookie) method which will adds fields to the HTTP response headers and sends back cookies to the browser and it happens one at a time. Browser support 20 cookies for each Web server all together 300 cookies total and this may limit cookie size to the 4 KB each

Browser returns back cookies to the requester servlet by adding fields to HTTP request headers. Cookies can be retrieved from request by using the HttpServletRequest.getCookies() method. Several cookies may have same name but different path attributes.

How to create Cookies:

Cookie cookie = new Cookie(“key”,”value”);

  • Session tracking API: Servlet API provides several methods and classes which is specifically designed to handle the session tracking on behalf of servlet. This provides all the boiler plate code to manage the session and it also covers all four technique of session tracking. Here servlet container manages the session tracking task where used need not to write their own implementation of session tracking. As it sounds it’s best of which is discussed above where container will be taken care of all management and session tracking.

Creating new OR Accessing the Session:

To create new session or gain access to the existing session use the HttpServletRequest method getSession() following below example:

HttpSession mySession = request.getSession();

getSession() method returns valid session object associated with in the request identified in the session cookie that is encapsulated in request object. Calling method with no arguments creates new session if one does not exist that is associated with request. Calling method with Boolean argument creates session only if the argument is true.

The following example shows doPost() method from servlet that only performs the servlets main functions where if session is present. Please note that the false parameter to getSession() prevents servlet from creating new session if one does not already exist:

public void doPost (HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
 {
        if ( HttpSession session = req.getSession(false) ) {
           // session retrieved, continue with servlet operations
        }
        else{
           // no session, return an error page
        }
}

Reference:

One thought on “Session Tracking Java Web Application”
  1. Informative and excellent article!
    I have found it very practical and understanding, the session tracking methods are important to know as java developer.This is considered as the best among other methods and there is no need for the user for explicit usage of java servlets.Thanks for sharing!

Leave a Reply

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