HTTP is a stateless protocol, which means that each time a client retrieves a web page, a separate server connection is opened, so the server does not record any information from previous client requests.
There are three ways to maintain a client-server session:
A web server can assign a unique session ID as a cookie to represent each client and identify subsequent requests from that client.
This may not be an efficient way, because many times browsers do not necessarily support cookies, so we do not recommend using this method to maintain the session.
A web server can send a hidden HTML form field and 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 automatically be included in the GET or POST data. Whenever the browser sends a request, the value of session_id can be used to save traces of different browsers.
This approach may be an efficient approach, but clicking a hyperlink in an <A HREF> tag does not generate a form submission event, so hidden form fields do not support universal session tracking.
You can add some additional data after each URL to distinguish the session, and the server can associate the session identifier based on this data.
For example, http://w3cschool.cn/file.htm;sessionid=12345, the session identifier is sessionid=12345, the server can use this data to identify the client.
In comparison, rewriting the URL is a better way, and it will work even if the browser does not support cookies, but the disadvantage is that you must dynamically specify the session ID for each URL, even if it is a simple HTML page.
In addition to the above methods, JSP uses the HttpSession interface provided by servlet to identify a user and store all access information of this user.
By default, JSP allows session tracking, and a new HttpSession object will be automatically instantiated for new clients. Disabling session tracking requires explicitly turning it off, which is accomplished by setting the value of the session attribute in the page directive to false, as follows:
<%@ page session="false" %>
The JSP engine exposes the underlying session object to developers. Since the session object is provided, developers can easily store or retrieve data.
The following table lists some important methods of the session object:
SN | Method & Description |
---|---|
1 | public Object getAttribute(String name) returns the object bound to the specified name in the session object, or null if it does not exist. |
2 | public Enumeration getAttributeNames() returns all object names in the session object |
3 | public long getCreationTime() returns the time when the session object was created, in milliseconds, starting from the early morning of January 1, 1970 |
4 | public String getId() returns the ID of the session object |
5 | public long getLastAccessedTime() returns the last access time of the client, in milliseconds, starting from the early morning of January 1, 1970 |
6 | public int getMaxInactiveInterval() returns the maximum time interval, in seconds, during which the servlet container will keep the session open |
7 | public void invalidate() invalidates the session and unbinds any objects bound to the session. |
8 | public boolean isNew( returns whether it is a new client, or whether the client refuses to join the session |
9 | public void removeAttribute(String name) removes the object with the specified name in the session |
10 | public void setAttribute(String name, Object value) uses the specified name and value to generate an object and bind it to the session |
11 | public void setMaxInactiveInterval(int interval) is used to specify the time, in seconds, during which the servlet container will keep the session valid. |
This example describes how to use the HttpSession object to obtain the creation time and last access time. We will associate a new session object with the request object if it does not already exist.
<%@ page import="java.io.*,java.util.*" %><% // Get the session creation time Date createTime = new Date(session.getCreationTime()); // Get the time of the last page visited Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check whether the web page is visited by a new user if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %><html><head><title>Session Tracking </title></head><body><center><h1>Session Tracking</h1></center><table 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>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td></tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td></tr> <tr> <td>Number of visits</td> <td><% out.print(visitCount); %></td></ tr> </table> </body></html>
Try to access http://localhost:8080/main.jsp. The following results will be obtained when running for the first time:
Visit again and you will get the following results:
After processing a user's session data, you have the following 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 validity period:
Call the public void setMaxInactiveInterval(int interval) method to set the session timeout.
Logout user:
Servers that support servlet version 2.4 can call the logout() method to log out the user and invalidate all related sessions.
Configure web.xml file:
If you are 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 in seconds. If 15 minutes is configured in web.xml, the getMaxInactiveInterval() method will return 900.