import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionSnoop extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session object, create one if necessary HttpSession session = req.getSession(true); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer)session.getValue("snoop.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.putValue("snoop.count", count); out.println("SessionSnoop"); out.println("

Session Snoop

"); // Display the hit count for this page out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.")); out.println("

"); out.println("

Here is your saved session data:

"); String[] names = session.getValueNames(); for (int i = 0; i < names.length; i++) { out.println(names[i] + ": " + session.getValue(names[i]) + "
"); } out.println("

Here are some vital stats on your session:

"); out.println("Session id: " + session.getId() + "
"); out.println("New session: " + session.isNew() + "
"); out.println("Creation time: " + session.getCreationTime()); out.println("(" + new Date(session.getCreationTime()) + ")
"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("(" + new Date(session.getLastAccessedTime()) + ")
"); out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "
"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromUrl() + "
"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "
"); out.println("

Here are all the current session IDs"); out.println("and the times they've hit this page:

"); HttpSessionContext context = session.getSessionContext(); Enumeration ids = context.getIds(); while (ids.hasMoreElements()) { String id = (String)ids.nextElement(); out.println(id + ": "); HttpSession foreignSession = context.getSession(id); Integer foreignCount = (Integer)foreignSession.getValue("snoop.count"); if (foreignCount == null) out.println(0); else out.println(foreignCount.toString()); out.println("
"); } out.println("

Test URL Rewriting

"); out.println("Click here"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println(""); } }