O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.6. Tracking Session Activity in JSPs

Problem

You want to find out a session's creation time and last-accessed time using JSPs.

Solution

Use the JSTL to get access to the JSP's associated HttpSession object. Then call the HttpSession.getCreationTime( ) and HttpSession.getLastAccessedTime( ) methods on that object.

Discussion

It is very easy to keep track of session activity in a JSP; you just use slightly different methods and tools compared to those used with a servlet. Example 11-8 uses the out custom action from the JSTL 1.0 to display information about the current session. Chapter 24 describes the JSTL and its associated EL in more detail.

Example 11-8. Tracking sessions using the JSTL

<%@page contentType="text/html"%><%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<html>
  <head><title>View Session JSP </title></head>
  <body>
    <h2>Session Info From A JSP</h2>

    The session id: <c:out value="${pageContext.session.id}"/><br><br>

    The session creation time as a long value: 
      <c:out value="${pageContext.session.creationTime}"/><br><br>

    The last accessed time as a long value: 
      <c:out value="${pageContext.session.lastAccessedTime}"/><br><br>

  </body>
</html>

This JSP uses a taglib directive to make the custom actions that are part of the core tag library available. By convention, the uri attribute for the core tags is http://java.sun.com/jstl/core, and the prefix is c (you can create your own prefix in the taglib directive). With JSTL 1.1, the uri value is http://java.sun.com/jsp/jstl/core ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required