Wednesday, December 31, 2014

Session Tracking in HTTP Servlet Programming in Java

HTTP is stateless protocol. A web server can keep track of clients and distinguish them by using session. This helps in delivering customized services for each client. The server identifies each client with session tracking
  • Each client is associated with javax.servlet.http.HttpSession object
  • Any set of arbitrary java objects can be saved in session object
  • getSession() method is used to retrieve the current HttpSession object. This method is in request object.
    • public HttpSession HttpServletRequest.getSession() //create new if not exist
    • public HttpSession HttpServletRequest.getSession(boolean create)
    • This gets or creates new one if create argument is set and returns HttpSession object otherwise return null
  • putValue() method is used to add data to HttpSession object
    • public void putValue(String name, Object value)
  • getValue() method is used to retrieve data from the session object
    • public Object HttpSession.getValue(String name)
  • getValueNames() method is used to retrieve array of all name-value pairs bound to session
    • public String[] HttpSession.getValueNames()
  • removeValue() method removes values from the session
    • public void HttpSession.removeValue(Strin name)
  • All these methods throw throws java.lang.IllegalStateException

Example implementing hit counter using session tracking in Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionTracker extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws servletException, IOException{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    //gets the current session object, create one if necessary (true)
    HttpSession session = request.getSession(true);
    //increment the hit count ofr this page. The value is saved
    //in this client's session under the name "tracker.count"
    Integer count = (Integer)session.getValue("tracker.count");
    If (count==null)
      count=new Integer(1);
    else
      count = new integer(count.intValue()+1);
    session.putValue("tracker.count",count);
    out.println("<html><head><title>Session tracker</title></head>");
    out.println("<body><h1>Session Tracking Demo</h1>");
    out.println("You visited this page "+ count + " times");
    out.println("<h2>Your Session Data</h2>");
    String[] names = session.getValueNames();
    for (int i=0;i<names.length;i++){
      out.println(names[i]+": "+session.getValue(names[i]+"<br>");
    }
    out.println("</body></html>");
}}

No comments:

Post a Comment