Tracking User Session by Servlets

HTTP is a stateless protocol, and a Web application, such as a shopping cart, needs a mechanism of tracking user session over multiple HTML pages. A session is defined as a series of related browser requests that come from the same client during a certain period of time. Servlets provide the following mechanisms of tracking sessions. Notice that in all these techniques, some form of token is passed between the client and the server.

  • Hidden fields

  • HTTP cookies

  • HTTPSession object

  • URL rewriting

In the following section, we'll explore each technique.

Tracking User Session Using Hidden Fields

This mechanism tracks user session in a hidden field of an HTML page and passes the data between the client and the server. The advantages of using this technique are its easy implementation, and that session state is not saved on the server side. Using a large amount of user data in the hidden fields will degrade application performance. Additionally, hidden fields are limited to storing only string values, which can be exposed in the generated HTML source unless encrypted to preserve user privacy. An example of an HTML page with hidden fields is as follows:

<FORM METHOD="POST" ACTION="/servlet/SignOnServlet">
...
<INPUT TYPE=hidden NAME="userid" VALUE="mary">
<INPUT TYPE=hidden NAME="type" VALUE="student">
...
</FORM>

In this technique, no data is stored on the client disk storage; only hidden fields are passed between the browser and the Web container.

Tracking User Session Using Cookies

This mechanism of session tracking is used for storing limited amount of user data on the client side. A cookie is a piece of data that the server creates to store user information and asks the Web browser to save locally on the user's disk. A cookie is identified by the URL it originated from. Each time a browser visits the same server (URL), it sends all cookies relevant to that server with the HTTP request. Cookies are useful for identifying clients as they return to the server.

Each cookie has a name and a value. A browser that supports cookies generally allows each server domain to store up to 20 cookies of up to 4KB of ASCII data per cookie. Cookies cannot store Unicode or binary values. Users can disable or enable cookies from the browser.

The following listing creates a SignOnCookie, gives it the value "mary" as a user ID, and adds it to the HttpServletResponse object of the service method:

// Create a cookie
Cookie myCookie = new Cookie("SignOnCookie", "mary");
myCookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(myCookie);

When the Web browser receives the response, it stores all the cookies on the user's disk, provided that the user has enabled cookies. The following listing illustrates how a returning client can be recognized by the Web application:

public class CheckServlet extends HttpServlet{
 public void service(HttpServletRequest req, HttpServletResponse res){
   Cookie myCookie = null;
   HttpSession session = req.getSession(false);
    if (session==null) {
      // Try to retrieve the cookie from the request.
      Cookie[] cookies = req.getCookies();
      for(int i=0; i < cookies.length; i++) {
        myCookie = cookies[i];
        if (myCookie.getName().equals("SignOnCookie")) {
          isFound = true;
          break;
          }
      }
      if (isFound == true) {
        // Create a new session for this user.
        //session = request.getSession (true);
        session.setAttribute("mary", myCookie.getValue());
        // Refresh cookie to live indefinitely.
        myCookie.setMaxAge(Integer.MAX_VALUE);
        // Add the cookie to the response
        res.addCookie(myCookie);
      }
   }
 }
}

The cookie in the preceding example is set not to expire. Because cookies accept only string values, you should cast to and from the desired type that you want to store in the cookie.

Tracking User Session Using HttpSession

This mechanism tracks the user session by storing all session information on the server side. Only a small piece of data (session ID) is stored on the client side and passed between the client and server for each request. According to the Servlet API, each servlet can access a server-side session by using its HttpSession object. You access the HttpSession object in the service() method of the servlet by using the HttpServletRequest object as follows:

HttpSession session = request.getSession(true);

A session is associated automatically with a particular client. An HttpSession object is created if one does not already exist for that client. Each client is matched with its particular session object by passing a session ID. The session object lives on the Web container for the lifetime of the session, during which the session object accumulates data related to that client. You can add or remove data from the session object as necessary, which will be maintained in the servlet context. In the following example, the service() method counts the number of hits that a client requests the servlet during one session:

public void service(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {
  // Get the client session associated with this request
  PrintWriter out = res.getWriter();
  HttpSession session = req.getSession(true);
  Integer value = (Integer) session.getAttribute("mySession.hits");
  if (value == null)
     value = new Integer (1);
  else
     value = new Integer (value.intValue () + 1);
  // Set the new name/value pair
  session.setAttribute("mySession.hits", value);
  // Output the HTML page
  out.print("<HTML><head></head><body>");
  out.print("You have visited this page ");
  out.print(value + " times!");
  out.println("<br>Session ID: " + session.getId());
  out.println("<br>Session creation time: " +
                session.getCreationTime());
  out.println("<br>Last accessed time: " +
                session.getLastAccessedTime());
  out.print("</body></html>");
 }

The HttpSession mechanism gives better performance because it stores the session data in memory and reduces network overhead. Only the session ID will be passed between the client and the server. The HttpSession object can hold data such as shopping carts and visit history, but it is not used to hold user profiles.

Tracking User Session Using URL Rewriting

This technique is used mainly if the users disable cookies from their browsers. URL rewriting allows servlets to append a user session ID at the end of any generated link (URL). URL rewriting resulted in moderate performance because the extra data must be passed between the client and the server for each request. Nonetheless, only a limited amount of user data can pass through URL rewriting. The Java servlet API provides two methods in the HttpResponse interface to encode the URLs. The encodeURL() method encodes the specified URL by appending the session ID to it. The following code shows an example of how URL rewriting may be used:

HttpSession session = req.getSession(true);
res.setContentType("text/html");
PrintWriter out = res.getWriter();
...
// URL Rewriting

String url = res.encodeURL("/servlet/SignOnServlet");
// Make a link to the URL rewritten
out.println("<A HREF="" + url + ""> Login </A>");
...

The servlet will append the session ID to the URL. The new URL will look like this:

http://www.mysite.com/servlet/SignOnServlet;jsessionid=123456

All URLs generated by a servlet should be run through the encodeURL() method. URL rewriting is a useful technique when users have disabled cookies in their browsers.

Working with Servlets as Delegates to EJBs

One of the primary tasks of servlets is to work as delegates for Web browsers to access an EJB indirectly. The following example illustrates how to access the StudentFacade EJB from our University Registration System (see Figure 7.5). Immediately after it creates the SignOnServlet instance, the Web container calls the instance's init() method. This method looks up the EJB home in the JNDI service, and then creates the bean:

public void init() throws ServletException {
    InitialContext ic = new InitialContext();
    StudentFacadeHome home = (StudentFacadeHome)
                        ctx.lookup("day21/StudentFacade");
    StudentFacade studentFacade = null;
    try {
       studentFacade = (StudentFacade) home.create();
       session.putValue("StudentFacade", studentFacade);
    catch(Exception e) {
        e.printStackTrace();
    }
  }
}

Figure 7.5. Servlets work as delegates of clients to EJBs.


When the user clicks on the Submit button of the HTML form, the Web container calls the doPost() method of the SignOnServlet. The doPost() method fetches the value of the Login Name and Password fields (entered by the end user), and then invokes the addUser() business method of the StudentFacade EJB:

public void doPost (HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    String loginName = req.getParameter("Login name");
    String password = req.getParameter("Password");
    try{
      studentFacade.addUser(loginName, password);
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      ...
    }catch{
     e.printStackTrace();
    }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.66