Creating or Accessing a Session in java

Creating or Accessing a Session

To use a session, first create a session using the HttpServletRequest method getSession(). Once the session is established, examine and set its properties using the provided methods. If desired, set the session to time out after being inactive for a defined time period, or invalidate it manually. You can also bind objects to the session, which store them for use by other components.

This section includes the following topics:

Creating or Accessing a Session

Examining Session Properties

Binding Data to a Session

Invalidating 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.

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
Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *


Author: pramod kumar kumawat Mob: 9269727062
Free WordPress Themes - Download High-quality Templates