CodeGym /Java Course /Module 3. Java Professional /Working with Servlet Sessions

Working with Servlet Sessions

Module 3. Java Professional
Level 12 , Lesson 3
Available

4.1 Introduction to HttpSession

If several requests come from the same client, then they say that a session has been established between the client and the server. To control this process, the container has a special HttpSession object.

When a client makes a request to a servlet, the servlet container checks to see if the session ID parameter is present in the request. If there is no such parameter (for example, the client is contacting the server for the first time), then the servlet container creates a new HttpSession object and also assigns it a unique ID.

The session object is stored on the server, and the ID is sent in the response to the client, and by default is stored on the client in a cookie. Then, when a new request comes in from the same client, the servlet container retrieves the ID from it, and by that ID finds the correct HttpSession object on the server.

You can get the session object from a request (an HttpServletRequest object), on which you need to call the getSession() method. It returns an HttpSession object.

Why is a session needed? It can store information about the client between calls. She has something like a HashMap inside, in which you can store objects by keys. And some methods for this:

Methods Description
1 setAttribute(String name, Object o) Adds an object to the session
2 getAttribute(String name) Gets an object from the session
3 removeAttribute(String name) Removes an object from the session

Let's write a servlet that will sum up all the numbers passed to it from different requests:

public class CalculatorServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
         // Get the "sum" attribute from the session
        HttpSession session = request.getSession();
        Integer sum = (Integer) session.getAttribute("sum");
        //Handling the situation when the session does not yet have such an attribute
        if (sum == null)
            sum = 0;

         // Get the "n" parameter from the request
        String n = request.getParameter("n");
        sum += Integer.parseInt(n);

         // Write the "sum" attribute to the session
        session.setAttribute("sum", sum);

        // Print the HTML as a response to the browser
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head> <title> CalculatorServlet </title> </head>");
        out.println("<body>");
        out.println("<h1> Sum == " + sum + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

4.2 More about HttpSession

Is there anything else we haven't said about the HttpSession object?

First, it is the name J SESSION ID. It is under it that the session ID is stored in cookies. As you can see, it's pretty easy to remember: J+SESSION+ID.

Secondly, the session has a few more useful methods:

Methods Description
1 getAttributeNames() Returns a list of all keys stored in the session
2 getId() Returns the session ID (string)
3 isNew() Returns true if the session object was created in the current request
4 setMaxInactiveInterval(int seconds) Sets the session inactivity interval in seconds
5 invalidate() Removes all objects from the session

Here all the methods are obvious, but setMaxInactiveInterval()we will talk about a little more.

If the server stores tens of thousands of sessions, including the data of clients who visited it last month, then it will simply run out of memory. Therefore, there is a way to set the “session lifetime”.

If no one used the session for an interval of time, then it clears itself - all objects that it stored are deleted from it. This is done to save memory.

By default, this interval is 1800 seconds == 30 minutes. If you set the value to -1, then the session will be “eternal” and will be deleted only when the user closes the browser tab (well, or the client disconnects).

Examples:

// get all keys
Enumeration keys = session.getAttributeNames();
while( keys.hasMoreElements() ){
    System.out.println( (String) keys.nextElement() );
}
// set the inactivity interval
session.setMaxInactiveInterval(60*60*24);   // 1 day
session.setMaxInactiveInterval(-1); // until the browser is closed
// remove all data from the session
session.invalidate();
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION