Sun Java System Web Server 6.1 SP7 Programmer's Guide to Web Applications

Creating or Accessing a Session

To create a new session or gain access to an existing session, use the HttpServletRequest method getSession(), as shown in the following example:

HttpSession mySession = request.getSession();

getSession() returns the valid session object associated with the request, identified in the session cookie that is encapsulated in the request object. Calling the method with no arguments creates a session if one does not exist that is associated with the request. Additionally, calling the method with a Boolean argument creates a session only if the argument is true.

The following example shows the doPost() method from a servlet that only performs the servlet's main functions, if the session is present. Note that the false parameter to getSession() prevents the servlet from creating a new session if one does not already exist:

public void doPost (HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
        if ( HttpSession session = req.getSession(false) ) {
           // session retrieved, continue with servlet operations
           // no session, return an error page


Note –

The getSession() method should be called before anything is written to the response stream.

For more information about getSession(), see the Java Servlet 2.3 specification.