Sun Java System Web Server 7.0 Developer's Guide to Java Web Applications

Examining Session Properties

Once a session ID has been established, use the methods in the HttpSession interface to examine session properties. Use the methods in the HttpServletRequest interface to examine request properties that relate to the session.

The following table shows the methods used to examine session properties.

Table 6–1 HttpSession Methods

HttpSession Method 

Description 

getCreationTime()

Returns the session time in milliseconds since January 1, 1970, 00:00:00 GMT. 

getId()

Returns the assigned session identifier. An HTTP session's identifier is a unique string that is created and maintained by the server. 

getLastAccessedTime()

Returns the last time the client sent a request carrying the assigned session identifier (or -1 for a new session) in milliseconds since January 1, 1970, 00:00:00 GMT.

isNew()

Returns a Boolean value indicating that the session is new. A new session is one that the server has created and the client has not sent a request to it. This state means the client has not acknowledged or joined the session and may not return the correct session identification information when making its next request. 

For example:


String mySessionID = mySession.getId();
     if ( mySession.isNew() ) {
         log.println(currentDate);
        log.println("client has not yet joined session " + mySessionID);
     }

         

The following table shows the methods used to examine servlet request properties.

Table 6–2 HttpServletRequestMethods

HttpServletRequest Method  

Description  

getRequestedSessionId()

Returns the session ID specified with the request. This value might differ from the session ID in the current session if the session ID given by the client is invalid and a new session was created. Returns null if the request does not have a session associated with it. 

isRequestedSessionIdValid()

Checks whether the request is associated with a currently valid session. If the session requested is not valid, it is not returned through the getSession() method.

isRequestedSessionIdFromCookie()

Returns true if the request's session ID provided by the client is a cookie, or false otherwise.

isRequestedSessionIdFromURL()

Returns true if the request's session ID provided by the client is a part of a URL, or false otherwise.

For example:


if ( request.isRequestedSessionIdValid() ) {
        if ( request.isRequestedSessionIdFromCookie() ) {
           // this session is maintained in a session cookie
         }
        // any other tasks that require a valid session
      } else {
        // log an application error
      }