This chapter describes how to create and manage a session that allows user and transaction information to persist between interactions.
Introducing Sessions
How to Use Sessions
HttpSession mySession = request.getSession();
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if ( HttpSession session = req.getSession(false) ) { // session retrieved, continue with servlet operations } else // no session, return an error page } }
String mySessionID = mySession.getId(); if ( mySession.isNew() ) { log.println(currentDate); log.println("client has not yet joined session " + mySessionID); }
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 }
Some objects may require that you know when they are placed into, or removed from, a session. You can obtain this information by implementing the HttpSessionBindingListener interface in those objects. When your application stores data in or removes data from the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, methods in the interface automatically notify the object that it has been bound or unbound.
To invalidate a session manually, simply call the following method:
session.invalidate();
To set a timeout for distributable sessions, set the following line in the SessionInfo section of the application configuration file appInfo.ntv:
"timeout" Int "timeout",
session.setMaxInactiveInterval(int timeout).
domain=".mydomain.com"; path="/"; //make entire domain visible isSecure=true; if ( setSessionVisibility(domain, path, isSecure) == GXE.SUCCESS ) { // session is now visible to entire domain }