Easy Tutorial
❮ Jstl Format Setbundle Tag Jsp Intro ❯

JSP Session

HTTP is a stateless protocol, which means that each time a client retrieves a webpage, it must open a separate connection to the server, and thus the server does not retain any information about previous client requests.

There are three methods to maintain a session between the client and the server:


Cookies

The web server can assign a unique session ID as a cookie to each client, to identify the client's subsequent requests.

This may not be an effective method, as browsers do not always support cookies, so we do not recommend using this method to maintain sessions.


Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID, like this:

<input type="hidden" name="sessionid" value="12345">

This entry means that when the form is submitted, the specified name and value will be automatically included in the GET or POST data. Whenever the browser sends a request, the value of session_id can be used to preserve the trail of different browsers.

This method may be effective, but it does not support general session tracking when hyperlinks in &lt;A HREF> tags are clicked, as no form submission event occurs.


URL Rewriting

You can append some additional data to each URL to distinguish sessions, and the server can associate these data with the session identifier.

For example, http://w3cschool.cc/file.htm;sessionid=12345, the session identifier is sessionid=12345, and the server can use this data to identify the client.

Compared to other methods, URL rewriting is a better way to maintain sessions, as it works even if the browser does not support cookies. However, the drawback is that you must dynamically specify the session ID for each URL, even if it's a simple HTML page.


Session Object

In addition to the above methods, JSP utilizes the HttpSession interface provided by the servlet to identify a user and store all access information for that user.

By default, JSP allows session tracking, and a new HttpSession object is automatically instantiated for a new client. Disabling session tracking requires explicitly turning it off by setting the session attribute value to false in the page directive, like this:

<%@ page session="false" %>

The JSP engine exposes the implicit session object to developers. With the session object provided, developers can easily store or retrieve data.

The following table lists some important methods of the session object:

S.N. Method & Description
1 public Object getAttribute(String name) Returns the object bound to the session with the specified name, or null if no object is bound under the name
2 public Enumeration getAttributeNames() Returns the names of all objects bound to the session
3 public long getCreationTime() Returns the time when the session was created, in milliseconds since midnight January 1, 1970 GMT
4 public String getId() Returns the session ID
5 public long getLastAccessedTime() Returns the last time the client accessed the session, in milliseconds since midnight January 1, 1970 GMT
6 public int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep the session open
7 public void invalidate() Invalidates the session and unbinds any objects bound to it
8 public boolean isNew() Returns whether the session is new to the client, or if the client has not joined the session
9 public void removeAttribute(String name) Removes the object bound to the session with the specified name
10 public void setAttribute(String name, Object value) Binds an object with the specified name and value to the session
11 public void setMaxInactiveInterval(int interval) Specifies the time interval, in seconds, that the servlet container will keep the session valid

JSP Session Application

This example describes how to use the HttpSession object to obtain the creation time and the last access time. We will associate a new session object with the request object if it does not already exist.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.,java.util." %> <% // Get session creation time Date createTime = new Date(session.getCreationTime()); // Get the last accessed time of the page Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to tutorialpro.org Example"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD");

// Check if the page has a new visitor if (session.isNew()){ title = "Welcome to tutorialpro.org Example"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } else { visitCount = (Integer)session.getAttribute(visitCountKey); visitCount += 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); } %> <html> <head> <title>Session Tracking</title> </head> <body>

<h1>Session Tracking</h1>

<table border="1" align="center"> <tr bgcolor="#949494"> <th>Session Info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>Last Access Time</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Visit Count</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>


Try visiting **http://localhost:8080/testjsp/main.jsp**. The first run will give you the following result:

Upon revisiting, you will get the following result:

---

## Deleting Session Data

When you are done with the session data, you have several options:

- **Remove a specific attribute:**

Call the `public void removeAttribute(String name)` method to remove the specified attribute.

- **Delete the entire session:**

Call the `public void invalidate()` method to invalidate the entire session.

- **Set session timeout:**

Call the `public void setMaxInactiveInterval(int interval)` method to set the session timeout.

- **Log out the user:**

For servers supporting servlet 2.4, call the `logout()` method to log out the user and invalidate all related sessions.

- **Configure the web.xml file:**

If using Tomcat, you can configure the web.xml file as follows:

<session-config> <session-timeout>15</session-timeout> </session-config>


The timeout is in minutes, and the default timeout in Tomcat is 30 minutes.

The getMaxInactiveInterval() method in Servlet returns the timeout interval in seconds. If 15 minutes is configured in web.xml, the getMaxInactiveInterval() method will return 900.

❮ Jstl Format Setbundle Tag Jsp Intro ❯