JSP/Servlet | Sessions and Cookies | Basic Session Operations and Usage

Cookies are useful for storing small values, but they cannot do much beyond that. They are not suitable for storing complex values or large data. However, there are many cases where you want to store some value for each user who accesses the site. For example, in a shopping cart, it is very useful if you can keep information about products placed in the cart.

When you want to store data that is more complex and larger than cookies for each user, use a session. A session is a feature that continues while the server and client, or browser, remain connected. By storing values in this session, you can store and manage data for each client.

Sessions are provided as a class named HttpSession. In fact, you do not need to create an instance yourself. An implicit object named session is included from the beginning, and you can use it to manipulate the session.

Saving and getting session values

The session provides methods for saving and getting values.

Save a value

session.setAttribute(name, value);

Get a value

Object variable = session.getAttribute(name);

Session values are configured in the form of attributes. You set an attribute with setAttribute and obtain the specified attribute with getAttribute. However, the concept of an “attribute” may feel unclear to many people. For that reason, methods in a simpler “set and get values” form are also provided.

Save a value

session.putValue(name, value);

Get a value

Object variable = session.getValue(name);

These two methods are actually completely identical in behavior. setAttribute and putValue do the same thing, and getAttribute and getValue are also the same. You can of course retrieve a value set with setAttribute using getValue, and the reverse is also true. Use whichever style you prefer.

Session connection time and release

A session starts when the connection begins and remains available while the connection is active. If there is no access for a certain amount of time, the session ends and all information stored in the session is deleted. When the browser is closed, the server is not notified separately, so the session actually remains alive for a while. It disappears after a certain amount of time.

HttpSession also provides methods related to session start time, elapsed time, and ending the session. They are summarized below.

Get the session creation time

long variable = session.getCreationTime();

Get the last access time

long variable = session.getLastAccessedTime();

Invalidate the session

session.invalidate();

getCreationTime and getLastAccessedTime return values in milliseconds since the standard PC date, midnight on January 1, 1970. invalidate invalidates the session, and after calling it, session methods and similar operations can no longer be used.

Specifying the session retention time

The session retention time is determined by the default setting of the WAS. Let’s look at how to increase the session retention time to an arbitrary value.

Specify the retention time in code

session.setMaxInactiveInterval(seconds);
  • If the session retention time is one hour, enter “3600”.

Specify the retention time in WEB-INF/web.xml

<session-config>
    <session-timeout>minutes</session-timeout>
</session-config>
  • If the session retention time is one hour, enter “60”.

Both methods specify the retention time for the session in the same way. If you want the session to continue without specifying a retention time, enter 0. The session retention time is renewed whenever the browser of the user who created that session makes a request. Setting a long session retention time is not good for security, so use it appropriately.

Trying sessions

Now let’s actually use a session. If we do the same thing as the previous example, it is hard to understand sessions clearly, so this time let’s create something that accumulates sent messages.

Create an example like the following.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    String flg = request.getParameter("check");
    if (flg != null) {
        session.invalidate();
        session = request.getSession();
    }

    long create = session.getCreationTime();
    long last = session.getLastAccessedTime();
    long time = (last - create) / 1000;
    if (time < 0)
        time = 0;

    String input = request.getParameter("input");
    if (input == null)
        input = "";

    ArrayList<String> msgs = (ArrayList<String>) session.getValue("messages");
    if (msgs == null)
        msgs = new ArrayList<String>();

    if (!input.equals(""))
        msgs.add(0, input);

    session.putValue("messages", msgs);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample jsp</title>
<style>
h1 {
    font-size: 16pt;
    background: #AAFFAA;
    padding: 5px;
}
</style>
</head>
<body>
    <h1>Sample jsp page</h1>
    <p>This page is a sample.</p>
    <table>
        <form method="post" action="helo.jsp">
            <tr>
                <td>Input</td>
                <td><input type="text" id="input" name="input"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="checkbox" id="check" name="check"> <label for="check">Reset</label></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send"></td>
            </tr>
        </form>
    </table>
    <hr>
    <p>(<%=time%> sec.)</p>
    <ol>
        <%
            for (int i = 0; i < msgs.size(); i++) {
        %>
        <li><%=msgs.get(i)%></li>
        <%
            }
        %>
    </ol>
</body>
</html>

When you access it, a screen with an input field appears. If you write something there and send it, it is displayed below. Each time you send a message, it is added to the top of the list. If you turn on the “Reset” checkbox when sending, the session is reset and the new message is added.

Notes on using sessions in GAE

If you run this session sample on Google App Engine, be careful that sessions must be explicitly enabled in GAE. Open the project’s appengine-web.xml file. This is an XML file that contains various GAE settings. Inside it is the <appengine-web-app> tag, where initial settings are written. Add the following tag inside that tag.

<sessions-enabled>true</sessions-enabled>

Now sessions can be used. If you forget this, session functionality will not work, so be careful.

This time, an ArrayList is stored in the session. Every time a message is sent, it is added to this ArrayList.

ArrayList<String> msgs = (ArrayList<String>)session.getValue("messages");
if (msgs == null)
    msgs = new ArrayList<String>();

First, get the ArrayList stored under “messages” with getValue. If it is null, create a new ArrayList instance.

Once the ArrayList is ready, add the submitted text to the beginning and store it in the session again.

session.putValue("messages", msgs);

The sample displays the elapsed time in seconds since the session started. This is simply calculated in advance and stored in a variable, then displayed with a <%= %> tag.

long create = session.getCreationTime();
long last = session.getLastAccessedTime();
long time = (last - create) / 1000;
if (time < 0)
    time = 0;

Get getCreationTime and getLastAccessedTime into variables, subtract the start time from the last access time, and divide by 1000 to get the elapsed seconds. It is surprisingly simple. Finally, let’s look at the processing when the “Reset” checkbox is on.

String flg = request.getParameter("check");
if (flg != null) {
    session.invalidate();
    session = request.getSession();
}

If a checkbox is checked, its value is sent. If it is off, the value itself is not sent. Therefore, if the value obtained with request.getParameter("check") is null, it is off; if it is not null, it is on.

When it is on, invalidate deletes the session. After that, the session must be started again and the submitted values must be stored. That is why request.getSession() is used to obtain HttpSession again. The implicit object session can be obtained from request with getSession.

With this, you can now perform basic operations such as storing session values, ending a session, and restarting it.