package SessionServlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Chapter 10, Listing 5 public class SessionServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { // Set the content type of the response res.setContentType("text/html"); // Get output stream and writers OutputStream out = res.getOutputStream(); PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( out ) ); // Determine whether an existing session exists HttpSession session = req.getSession(false); // If no existing session, add a visit value of one to a new session if(session == null) { session=req.getSession(true); session.putValue ("VisitCount", "1"); } pw.println("
");

      pw.println("session.isNew()="+session.isNew());
      pw.println("session.getCreationTime()="+ new java.util.Date( session.getCreationTime()));
      pw.println("session.getID()="+session.getId());
      pw.println("session.getLastAccessedTime()=" + new java.util.Date(session.getLastAccessedTime()));
      
	  // Modify a session variable, so state information is changed from one invocation
	  // to another of this servlet
	  String strCount = (String) session.getValue("VisitCount");
	  pw.println("No. of times visited = " + strCount);

	  // Increment counter
	  int count = Integer.parseInt(strCount);  count++;
	  // Place new session data back for next servlet invocation
	  session.putValue("VisitCount", Integer.toString(count));
      
	  pw.println ("
"); pw.flush(); } }