JSP Session
HTTP is a stateless protocol, which means that each time a client retrieves a web page, it must open a separate server connection, so the server does not record any information about previous client requests.
There are three ways to maintain a session between the client and the server:
Cookies
A web server can assign a unique session ID as a cookie to represent each client, used to identify that client's subsequent requests.
This may not be an effective approach, because browsers do not necessarily support cookies in many cases, so we do not recommend using this method to maintain sessions.
Hidden Form Fields
A web server can send a hidden HTML form field and a unique session ID, as follows:
This entry means that when the form is submitted, the specified name and value will be automatically included in the GET or POST data. Every time the browser sends a request, the value of session_id can be used to keep track of different browsers.
This approach may be effective, but clicking ahyperlink in a tag does not generate a form submission event, so hidden form fields do not support general session tracking either.
URL Rewriting
You can append some extra data to each URL to distinguish sessions, and the server can use this data to associate a session identifier.
For example, in http://w3cschool.cc/file.htm;sessionid=12345, the session identifier is sessionid=12345, and the server can use this data to identify the client.
By comparison, URL rewriting is a better approach that works even when the browser does not support cookies, but the drawback is that you must dynamically specify the session ID for every URL, even if it is a simple HTML page.
The session Object
In addition to the above methods, JSP uses the HttpSession interface provided by the servlet to identify a user and store all of that user's access information.
By default, JSP allows session tracking, and a new HttpSession object is automatically instantiated for a new client. To disable session tracking, you must explicitly turn it off by setting the session attribute of the page directive to false, as follows:
<%@ page session="false" %>
The JSP engine exposes the implicit session object to developers. Because the session object is provided, developers can conveniently 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 specified name in the session, or null if it does not exist |
| 2 | public Enumeration getAttributeNames() Returns the names of all objects in the session |
| 3 | public long getCreationTime() Returns the time when the session was created, in milliseconds, counted from midnight on January 1, 1970 |
| 4 | public String getId() Returns the ID of the session object |
| 5 | public long getLastAccessedTime() Returns the time of the client's last access, in milliseconds, counted from midnight on 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 it |
| 8 | public boolean isNew() Returns whether this is a new client, or whether the client has refused to join the session |
| 9 | public void removeAttribute(String name) Removes the object with the specified name from the session |
| 10 | **public void setAttribute(String name, Object value) ** Creates an object with the specified name and value and binds it to the session |
| 11 | public void setMaxInactiveInterval(int interval) Specifies the time, in seconds, during which 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 one does not already exist.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<%
// 获取session创建时间
Date createTime = new Date(session.getCreationTime());
// 获取最后访问页面的时间
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Access the Runoob Tutorial instance again";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// 检测网页是否有新的访问用户
if (session.isNew()){
title = "Visit the Runoob Tutorial 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);
}
%>
Session 跟踪
Session 跟踪
Session 信息
值
id
<% out.print( session.getId()); %>
创建时间
<% out.print(createTime); %>
最后访问时间
<% out.print(lastAccessTime); %>
用户 ID
<% out.print(userID); %>
访问次数
<% out.print(visitCount); %>
Try accessing http://localhost:8080/testjsp/main.jsp ; on the first run you will get the following result:

Accessing it again will give the following result:

Deleting Session Data
After finishing 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 the session validity period:**
Call the public void setMaxInactiveInterval(int interval) method to set the session timeout.
- ** Log out the user:**
On servers that support servlet version 2.4, you can call the logout() method to log out the user and invalidate all associated sessions.
- ** Configure the web.xml file:**
If you are using Tomcat, you can configure the web.xml file as follows:
15
The timeout is measured in minutes; the default timeout in Tomcat is 30 minutes.
The getMaxInactiveInterval( ) method in servlets returns the timeout in seconds. If web.xml is configured with 15 minutes, the getMaxInactiveInterval( ) method will return 900.