// From "Professional Java Server Programming", Patzer et al., // Edition J2EE, Ch 9, pg 401 // Import Servlet Libraries import javax.servlet.*; import javax.servlet.http.*; // Import Java Libraries import java.io.*; import java.util.Date; public class sessionLifeCycle extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter ("action"); if (action != null && action.equals ("invalidate")) { // Called from the invalidate button, kill the session. // Get session object HttpSession session = request.getSession (); session.invalidate(); response.setContentType ("text/html"); PrintWriter out = response.getWriter (); out.println (""); out.println (""); out.println (" Session Lifecycle"); out.println (""); out.println (""); out.println (""); out.println ("

"); out.println ("Your session has been invalidated.

"); // Create a link so the user can create a new session. // The link will have a parameter builtin String lifeCycleURL = "/offutt/servlet/sessionLifeCycle"; out.println (""); out.println ("Create new session"); out.println (""); out.println (""); out.close(); } //end if else { // We were called either directly or through the reload button. // Get session object HttpSession session = request.getSession (); response.setContentType ("text/html"); PrintWriter out = response.getWriter (); out.println (""); // no-cache lets the page reload by clicking on the reload link out.println (""); out.println (""); out.println (" Session Lifecycle"); out.println (""); out.println (""); out.println (""); out.println ("

Session Life Cycle

"); out.print ("
Session Status: "); if (session.isNew()) { out.println ("New Session."); } else { out.println ("Old Session."); } // Get the session ID out.print ("
Session ID: "); out.println (session.getId()); // Get the created time, convert it to a Date object out.print ("
Creation Time: "); out.println (new Date (session.getCreationTime())); // Get the last time it was accessed out.print ("
Last Accessed Time: "); out.println (new Date(session.getLastAccessedTime())); // Get the max-inactive-interval setting out.print ("
Maximum Inactive Interval (seconds): "); out.println (session.getMaxInactiveInterval()); String lifeCycleURL = "/offutt/servlet/sessionLifeCycle"; out.print ("

"); out.println ("Invalidate the session"); out.print ("
"); out.println ("Reload this page"); out.println (""); out.println (""); out.close(); } //end else } // End doGet } //End sessionLifeCycle