Tracking HTTP sessions

Sessions are used to track client accesses and interactions. They answer user-access related questions, such as: How does a server know whether a client logged in? How does an on-line store keep tracking items that a user selected in her cart?. In this tutorial, we will see how to handle sessions using servlet.

Storing simple values

  1. Open the servletlabs project in the previous tutorial.
  2. Right click on the servletlabs project, select New→servlet. Name the package as: session.servlet and the class as: ShowSession.
  3. Insert the following codes into the doGet(…) function of the class ShowSession.

    		// Create a session object if it is already not created.
    		HttpSession session = request.getSession();
    		// Get session creation time.
    		Date createTime = new Date(session.getCreationTime());
    		// Get last access time of this web page.
    		Date lastAccessTime = new Date(session.getLastAccessedTime());
     
    		String heading;
    		Integer accessCount = 0;
    		String accessCountKey = "AccessCountKey";
    		String userID = "chan";
     
    		// Check if this is new comer on your web page.
    		if (session.isNew()){
    			heading = "Welcome, "+userID;
    			accessCount=0;
    		} 
    		else {
    			heading = "Welcome back";
    			accessCount = (Integer)session.getAttribute(accessCountKey);
    			accessCount = accessCount + 1;
    		}
    		session.setAttribute(accessCountKey, accessCount);
     
    		//session.invalidate();
     
    		// Set response content type
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
     
    		String docType =
    				"<!doctype html public \"-//w3c//dtd html 4.0 " +
    						"transitional//en\">\n";
    		out.println(docType +
    				"<html>\n" +
    				"<head><title> Servlet Session tutorial </title></head>\n" +
    				"<body>\n" +
    				"<h1 align=\"center\">" + heading + "</h1>\n" +
    				"<table border=\"1\" align=\"center\">\n" +
    				"<tr>\n" +
    				"  <th>Session info</th><th>value</th></tr>\n" +
    				"<tr>\n" +
    				"  <td>id</td>\n" +
    				"  <td>" + session.getId() + "</td></tr>\n" +
    				"<tr>\n" +
    				"  <td>Creation Time</td>\n" +
    				"  <td>" + createTime + 
    				"  </td></tr>\n" +
    				"<tr>\n" +
    				"  <td>Time of Last Access</td>\n" +
    				"  <td>" + lastAccessTime + 
    				"  </td></tr>\n" +
    				"<tr>\n" +
    				"  <td>User ID</td>\n" +
    				"  <td>" + userID + 
    				"  </td></tr>\n" +
    				"<tr>\n" +
    				"  <td>Number of visits</td>\n" +
    				"  <td>" + accessCount + "</td></tr>\n" +
    				"</table>\n" +
    				"</body></html>");
  4. Some errors appear because of the missing libraries. Click on the symbols x on the left and select to import the suggested libraries. Or you can manually insert the following lines in the import section.

    import javax.servlet.http.HttpSession;
    import java.io.PrintWriter;
    import java.util.Date;
  5. Right click on the ShowSession.java file, select Run As→Run on Server.
  6. The servlet is load in your web browser at: http://localhost:8080/servletlabs/ShowSession. If it's the first time you access to this URL, you'll get:


  7. Otherwise, you'll get:


Storing complex values

  1. Right click on the WebContent folder, select New→HTML File.
  2. Name it items.html and put the following codes between the <body> tags

    <form action="ListItems" method="POST">
      Item: <input type="text" name="newItem"><p>
      <input type="submit">
    </form>
  3. Save the file.
  4. Right click on the session.servlet package, select New→Servlet and name it ListItems.
  5. Insert the following codes to the doPost() function of the ListItems class

    		// Create a session object if it is already not created.
    		HttpSession session = request.getSession();
     
    		ArrayList<String> previousItems = (ArrayList<String>)session.getAttribute("previousItems");
    		if (previousItems == null) {
    			previousItems = new ArrayList<String>();
    		}
    		String newItem = request.getParameter("newItem");
    		if ((newItem != null) && (!newItem.trim().equals(""))) {
    			previousItems.add(newItem);
    		}
     
    		session.setAttribute("previousItems", previousItems);
     
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
    		String docType =
    				"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    						"Transitional//EN\">\n";
    		out.println(docType +
    				"<HTML>\n" +
    				"<HEAD><TITLE> List Items </TITLE></HEAD>\n" +
    				"<BODY>\n" +
    				"<H1> List of Item </H1>");
    		if (previousItems.size() == 0) {
    			out.println("<I>No items</I>");
    		} 
    		else {
    			out.println("<UL>");
    			for(String item: previousItems) {
    				out.println(" <LI>" + item);
    			}
    			out.println("</UL>");
    		}
    		out.println("</BODY></HTML>");
  6. Some errors appear because of the missing libraries. Click on the symbols x on the left and select to import the suggested libraries. Or you can manually insert the following lines in the import section.

    import javax.servlet.http.HttpSession;
    import java.util.ArrayList;
    import java.io.PrintWriter;
  7. Save the file.
  8. Right click on the items.html file, select Run As→Run on Server
  9. The items.html will be open at http://localhost:8080/servletlabs/items.html. Type an item and click on Submit Query


  10. You can back to the http://localhost:8080/servletlabs/items.html and repeat your submission. You'll get a list of submitted items


Exercises

  1. The session ID is stored on the server or at client side ? Where can we find it ?
  2. To remove a working session, we use the function session.invalidate();. So, could you please create a servlet that can remove a working session ? How do we check whether the session is removed ?
  3. Modify the ShowSession servlet in the tutorial to ask a user to input his [full name] and [date of birth] if she access the first time. If she is a returned user, compute the number of days to her birthday, and show her a message: “Hi, [full name]. There are [number of days] days to your birthday.”
  4. Modify the ListItems servlet in the tutorial to display also the number of times that an item was input.
teaching_assistant/servlet-jsp/servlet-session.txt · Last modified: 2013/07/08 08:44 (external edit)
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0