Friday, 7 November 2014

Session Tracking in Servlets



Session Tracking in Servlets

Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
session tracking

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:
  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

    Cookies in Servlet

    cookie is a small piece of information that is persisted between the multiple client requests.
    A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

    How Cookie works

    By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
    cookies in session tracking

    Types of Cookie

    There are 2 types of cookies in servlets.
    1.Non-persistent cookie
    2.Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.

Advantage of Cookies

  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.

Disadvantage of Cookies

  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.


Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

ConstructorDescription
Cookie()constructs a cookie.
Cookie(String name, String value)constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.
MethodDescription
public void setMaxAge(int expiry)Sets the maximum age of the cookie in seconds.
public String getName()Returns the name of the cookie. The name cannot be changed after creation.
public String getValue()Returns the value of the cookie.
public void setName(String name)changes the name of the cookie.
public void setValue(String value)changes the value of the cookie.

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:
  1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
  2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.
  1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object  
  2. response.addCookie(ck);//adding cookie in the response  

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
  1. Cookie ck=new Cookie("user","");//deleting value of cookie  
  2. ck.setMaxAge(0);//changing the maximum age to 0 seconds  
  3. response.addCookie(ck);//adding cookie in the response  

How to get Cookies?

Let's see the simple code to get all the cookies.
  1. Cookie ck[]=request.getCookies();  
  2. for(int i=0;i<ck.length;i++){  
  3.  out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie  
  4. }  

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.
cookies in session tracking

index.html

  1. <form action="servlet1" method="post">  
  2. Name:<input type="text" name="userName"/><br/>  
  3. <input type="submit" value="go"/>  
  4. </form>  

FirstServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5.   
  6. public class FirstServlet extends HttpServlet {  
  7.   
  8.   public void doPost(HttpServletRequest request, HttpServletResponse response){  
  9.     try{  
  10.   
  11.     response.setContentType("text/html");  
  12.     PrintWriter out = response.getWriter();  
  13.           
  14.     String n=request.getParameter("userName");  
  15.     out.print("Welcome "+n);  
  16.   
  17.     Cookie ck=new Cookie("uname",n);//creating cookie object  
  18.     response.addCookie(ck);//adding cookie in the response  
  19.   
  20.     //creating submit button  
  21.     out.print("<form action='servlet2'>");  
  22.     out.print("<input type='submit' value='go'>");  
  23.     out.print("</form>");  
  24.           
  25.     out.close();  
  26.   
  27.         }catch(Exception e){System.out.println(e);}  
  28.   }  
  29. }  

SecondServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class SecondServlet extends HttpServlet {  
  6.   
  7. public void doPost(HttpServletRequest request, HttpServletResponse response){  
  8.     try{  
  9.   
  10.     response.setContentType("text/html");  
  11.     PrintWriter out = response.getWriter();  
  12.       
  13.     Cookie ck[]=request.getCookies();  
  14.     out.print("Hello "+ck[0].getValue());  
  15.   
  16.     out.close();  
  17.   
  18.          }catch(Exception e){System.out.println(e);}  
  19.     }  
  20.       
  21.   
  22. }  

web.xml

  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>s1</servlet-name>  
  5. <servlet-class>FirstServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>s1</servlet-name>  
  10. <url-pattern>/servlet1</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. <servlet>  
  14. <servlet-name>s2</servlet-name>  
  15. <servlet-class>SecondServlet</servlet-class>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>s2</servlet-name>  
  20. <url-pattern>/servlet2</url-pattern>  
  21. </servlet-mapping>  
  22.   
  23. </web-app>  

Output

servlet cookie servlet cookies servlet cookies example
  1.  
  2.  

    2) Hidden Form Field

    In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.
    In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.
    Let's see the code to store value in hidden field.
    1. <input type="hidden" name="uname" value="Vimal Jaiswal">  
    Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

    Real application of hidden form field

    It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified.

    Advantage of Hidden Form Field

  3. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

  1. It is maintained at server side.
  2. Extra form submission is required on each pages.
  3. Only textual information can be used.

Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from another servlet.
Hidden Form Field in Servlet

index.html

  1. <form action="servlet1">  
  2. Name:<input type="text" name="userName"/><br/>  
  3. <input type="submit" value="go"/>  
  4. </form>  

FirstServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class FirstServlet extends HttpServlet {  
  6. public void doGet(HttpServletRequest request, HttpServletResponse response){  
  7.         try{  
  8.   
  9.         response.setContentType("text/html");  
  10.         PrintWriter out = response.getWriter();  
  11.           
  12.         String n=request.getParameter("userName");  
  13.         out.print("Welcome "+n);  
  14.           
  15.         //creating form that have invisible textfield  
  16.         out.print("<form action='servlet2'>");  
  17.         out.print("<input type='hidden' name='uname' value='"+n+"'>");  
  18.         out.print("<input type='submit' value='go'>");  
  19.         out.print("</form>");  
  20.         out.close();  
  21.   
  22.                 }catch(Exception e){System.out.println(e);}  
  23.     }  
  24.   
  25. }  

SecondServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. public class SecondServlet extends HttpServlet {  
  5. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  6.         try{  
  7.         response.setContentType("text/html");  
  8.         PrintWriter out = response.getWriter();  
  9.           
  10.         //Getting the value from the hidden field  
  11.         String n=request.getParameter("uname");  
  12.         out.print("Hello "+n);  
  13.   
  14.         out.close();  
  15.                 }catch(Exception e){System.out.println(e);}  
  16.     }  
  17. }  

web.xml

  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>s1</servlet-name>  
  5. <servlet-class>FirstServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>s1</servlet-name>  
  10. <url-pattern>/servlet1</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. <servlet>  
  14. <servlet-name>s2</servlet-name>  
  15. <servlet-class>SecondServlet</servlet-class>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>s2</servlet-name>  
  20. <url-pattern>/servlet2</url-pattern>  
  21. </servlet-mapping>  
  22.   
  23. </web-app>  
  24. 3)URL Rewriting

    In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:
    url?name1=value1&name2=value2&??
    A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.
    URL Rewriting

    Advantage of URL Rewriting

  25. It will always work whether cookie is disabled or not (browser independent).
  26. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

  1. It will work only with links.
  2. It can send Only textual information.

Example of using URL Rewriting

In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user in the query string and getting the value from the query string in another page.

index.html

  1. <form action="servlet1">  
  2. Name:<input type="text" name="userName"/><br/>  
  3. <input type="submit" value="go"/>  
  4. </form>  

FirstServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5.   
  6. public class FirstServlet extends HttpServlet {  
  7.   
  8. public void doGet(HttpServletRequest request, HttpServletResponse response){  
  9.         try{  
  10.   
  11.         response.setContentType("text/html");  
  12.         PrintWriter out = response.getWriter();  
  13.           
  14.         String n=request.getParameter("userName");  
  15.         out.print("Welcome "+n);  
  16.   
  17.         //appending the username in the query string  
  18.         out.print("<a href='servlet2?uname="+n+"'>visit</a>");  
  19.                   
  20.         out.close();  
  21.   
  22.                 }catch(Exception e){System.out.println(e);}  
  23.     }  
  24.   
  25. }  

SecondServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class SecondServlet extends HttpServlet {  
  6.   
  7. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  8.         try{  
  9.   
  10.         response.setContentType("text/html");  
  11.         PrintWriter out = response.getWriter();  
  12.           
  13.         //getting value from the query string  
  14.         String n=request.getParameter("uname");  
  15.         out.print("Hello "+n);  
  16.   
  17.         out.close();  
  18.   
  19.                 }catch(Exception e){System.out.println(e);}  
  20.     }  
  21.       
  22.   
  23. }  

web.xml

  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>s1</servlet-name>  
  5. <servlet-class>FirstServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>s1</servlet-name>  
  10. <url-pattern>/servlet1</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. <servlet>  
  14. <servlet-name>s2</servlet-name>  
  15. <servlet-class>SecondServlet</servlet-class>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>s2</servlet-name>  
  20. <url-pattern>/servlet2</url-pattern>  
  21. </servlet-mapping>  
  22.   
  23. </web-app> 
  24. 4) HttpSession interface

    In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks: bind objects view and manipulate information about a session, such as the session identifier, creation time, and last accessed time. 
HttpSession object

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:
  1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value from the session scope in another servlet. To set the attribute in the session scope, we have used the setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute method.

index.html

  1. <form action="servlet1">  
  2. Name:<input type="text" name="userName"/><br/>  
  3. <input type="submit" value="go"/>  
  4. </form>  

FirstServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5.   
  6. public class FirstServlet extends HttpServlet {  
  7.   
  8. public void doGet(HttpServletRequest request, HttpServletResponse response){  
  9.         try{  
  10.   
  11.         response.setContentType("text/html");  
  12.         PrintWriter out = response.getWriter();  
  13.           
  14.         String n=request.getParameter("userName");  
  15.         out.print("Welcome "+n);  
  16.           
  17.         HttpSession session=request.getSession();  
  18.         session.setAttribute("uname",n);  
  19.   
  20.         out.print("<a href='servlet2'>visit</a>");  
  21.                   
  22.         out.close();  
  23.   
  24.                 }catch(Exception e){System.out.println(e);}  
  25.     }  
  26.   
  27. }  

SecondServlet.java

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class SecondServlet extends HttpServlet {  
  6.   
  7. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  8.         try{  
  9.   
  10.         response.setContentType("text/html");  
  11.         PrintWriter out = response.getWriter();  
  12.           
  13.         HttpSession session=request.getSession(false);  
  14.         String n=(String)session.getAttribute("uname");  
  15.         out.print("Hello "+n);  
  16.   
  17.         out.close();  
  18.   
  19.                 }catch(Exception e){System.out.println(e);}  
  20.     }  
  21.       
  22.   
  23. }  

web.xml

  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>s1</servlet-name>  
  5. <servlet-class>FirstServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>s1</servlet-name>  
  10. <url-pattern>/servlet1</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. <servlet>  
  14. <servlet-name>s2</servlet-name>  
  15. <servlet-class>SecondServlet</servlet-class>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>s2</servlet-name>  
  20. <url-pattern>/servlet2</url-pattern>  
  21. </servlet-mapping>  
  22.   
  23. </web-app> 

No comments:

Post a Comment