JSP Session
核对 HTTP 无状态背景下的三种会话跟踪手段、HttpSession 隐式对象 11 个常用方法、会话访问计数示例,以及属性移除、会话销毁与 web.xml 超时换算规则。
学完这一章,你能够
- 核对 HTTP 无状态背景下的三种会话跟踪手段、HttpSession 隐式对象 11 个常用方法、会话访问计数示例,以及属性移除、会话销毁与 web.xml 超时换算规则。
HTTP 无状态与三种基础会话跟踪机制
HTTP 本身是无状态协议,客户端每次请求网页都独立建立通信而不自带历史上下文。要在多次请求之间维系用户会话,传统上有三类载体:其一是通过 Cookie 传递唯一会话标识(如 `JSESSIONID`),后续请求自动回传给服务器识别身份;但如果客户端禁用或限制 Cookie,则单纯依赖 Cookie 的方案会失效。
其二是利用隐藏表单域 `<input type="hidden" name="sessionid" value="12345">`,在提交 GET 或 POST 表单时随表单数据一并带回会话编号;但该方式仅在表单提交时生效,普通超链接 `<a>` 跳转不会触发表单提交,因此无法支撑通用的全站会话跟踪。
其三是 URL 重写,即在链接末尾附加路径参数(规范写法如 `/app/page.jsp;jsessionid=SID-1001`)以携带会话标识。它在浏览器禁用 Cookie 时仍可工作,但代价是必须动态改写页面中的每一个跳转链接(包括静态入口页面)。本站本地实测已核对三类载体的构造解析与 `<%@ page session="false" %>` 禁用声明。
HttpSession 隐式对象与常用方法
在 Servlet/JSP 体系中,容器基于 `javax.servlet.http.HttpSession` 接口为每个访问者维护会话状态,并默认在 JSP 中自动创建和暴露隐式对象 `session`。若某页面无需会话(例如纯静态模板或无状态接口),可通过 `<%@ page session="false" %>` 显式关闭自动创建,避免不必要的服务端内存开销;下方参考表汇总了 `HttpSession` 的 11 个核心方法。
JSP Session 访问计数应用与环回实测
典型的 Session 跟踪示例在进入页面时先读取 `session.getCreationTime()` 与 `session.getLastAccessedTime()` 并转为 `java.util.Date`,再依据 `session.isNew()` 区分首次访问与后续访问:首次访问初始化 `userID` 与 `visitCount = 0` 并存入会话;再次访问时取出 `visitCount` 加 1 写回并读取原有 `userID`(生产代码应先对 `getAttribute` 结果判空,避免先建会话后写入属性时触发空指针)。本站在 OpenJDK 1.8.0_492 下以本地环回 `HttpServer` 实测连续两次请求:首次响应下发 `Set-Cookie: JSESSIONID=SID-DEMO-01; Path=/; HttpOnly` 且返回 `isNew=true`、`visitCount=0`;第二次携带该 Cookie 访问返回 `isNew=false`、`visitCount=1` 且 `lastAccessedTime` 推进 5 秒。
清理会话数据与配置超时时间
会话结束或用户退出时可按粒度采取不同清理策略:仅删除单个键值时调用 `session.removeAttribute(String name)`;要彻底销毁会话并解绑全部属性时调用 `session.invalidate()`(销毁后再次读写属性会抛出 `IllegalStateException`);动态调整当前会话空闲超时则调用 `session.setMaxInactiveInterval(int interval)`(单位为秒)。在支持容器安全认证的环境中还可调用 `HttpServletRequest.logout()` 退出当前用户身份(注:`logout()` 实际由 Servlet 3.0 规范正式引入,旧资料常误述为 Servlet 2.4,且退出后仍建议显式调用 `session.invalidate()` 以清空业务会话数据)。
若要在部署描述符 `web.xml` 中统一指定全局会话超时,可配置 `<session-config><session-timeout>15</session-timeout></session-config>`。需要特别区分单位:`web.xml` 中 `<session-timeout>` 以分钟计(Tomcat 默认 30 分钟,即 1800 秒),而 `session.getMaxInactiveInterval()` 返回值以秒计——配置 15 分钟时该方法返回 `900`。本站离线实验已完整验证 `getAttributeNames()`、`removeAttribute()`、15 分钟换算 900 秒及 `invalidate()` 后抛出 `IllegalStateException`。
HttpSession 隐式对象常用方法
| 方法签名 | 作用说明 |
| public Object getAttribute(String name) | 返回与指定名称绑定的会话属性对象,不存在时返回 null。 |
| public Enumeration getAttributeNames() | 返回当前会话中全部属性名称的枚举集合。 |
| public long getCreationTime() | 返回会话创建时间戳(自 1970-01-01 00:00:00 GMT 起的毫秒数)。 |
| public String getId() | 返回容器分配给该会话的唯一字符串标识(如 JSESSIONID)。 |
| public long getLastAccessedTime() | 返回客户端最近一次携带该会话发出请求的时间戳(毫秒)。 |
| public int getMaxInactiveInterval() | 返回容器在无请求时保持会话有效的最大间隔(单位:秒)。 |
| public void invalidate() | 立即使当前会话失效并解绑全部已存储属性。 |
| public boolean isNew() | 判断该会话是否刚创建且客户端尚未确认加入会话。 |
| public void removeAttribute(String name) | 从当前会话移除指定名称对应的属性绑定。 |
| public void setAttribute(String name, Object value) | 将指定对象按名称绑定到当前会话;若值为 null 等价于移除。 |
| public void setMaxInactiveInterval(int interval) | 设置当前会话的最大空闲有效时长(单位:秒,负值表示永不超时)。 |
运行 OpenJDK 1.8 本地环回 HTTP 会话跟踪、属性管理与超时实测
展开查看收起
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExploreSession {
static class SimulatedHttpSession {
private final String id;
private final long creationTime;
private long lastAccessedTime;
private int maxInactiveInterval = 1800; // Tomcat default 30 min = 1800s
private boolean isNew = true;
private boolean valid = true;
private final Map<String, Object> attrs = new LinkedHashMap<>();
SimulatedHttpSession(String id, long nowMillis) {
this.id = id;
this.creationTime = nowMillis;
this.lastAccessedTime = nowMillis;
}
private void ensureValid() {
if (!valid) {
throw new IllegalStateException("Session already invalidated");
}
}
String getId() { return id; }
long getCreationTime() { ensureValid(); return creationTime; }
long getLastAccessedTime() { ensureValid(); return lastAccessedTime; }
int getMaxInactiveInterval() { return maxInactiveInterval; }
void setMaxInactiveInterval(int seconds) { this.maxInactiveInterval = seconds; }
boolean isNew() { ensureValid(); return isNew; }
void touch(long nowMillis) {
ensureValid();
this.isNew = false;
this.lastAccessedTime = nowMillis;
}
void setAttribute(String name, Object value) {
ensureValid();
if (value == null) {
attrs.remove(name);
} else {
attrs.put(name, value);
}
}
Object getAttribute(String name) {
ensureValid();
return attrs.get(name);
}
Enumeration<String> getAttributeNames() {
ensureValid();
return Collections.enumeration(new ArrayList<>(attrs.keySet()));
}
void removeAttribute(String name) {
ensureValid();
attrs.remove(name);
}
void invalidate() {
ensureValid();
attrs.clear();
valid = false;
}
boolean isValid() { return valid; }
}
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<>();
// Case 1: Three session tracking mechanisms (Cookie, Hidden Form Field, URL Rewriting)
Map<String, Object> trackExp = new LinkedHashMap<>();
trackExp.put("cookie_header", "JSESSIONID=SID-1001; Path=/; HttpOnly");
trackExp.put("hidden_input_name", "sessionid");
trackExp.put("hidden_input_value", "12345");
trackExp.put("rewritten_url", "/app/page.jsp;jsessionid=SID-1001");
trackExp.put("extracted_url_sid", "SID-1001");
trackExp.put("page_session_false_directive", "<%@ page session=\"false\" %>");
String hiddenHtml = "<input type=\"hidden\" name=\"sessionid\" value=\"12345\">";
Matcher mName = Pattern.compile("name=\"([^\"]+)\"").matcher(hiddenHtml);
Matcher mVal = Pattern.compile("value=\"([^\"]+)\"").matcher(hiddenHtml);
mName.find();
mVal.find();
String rewritten = "/app/page.jsp" + ";jsessionid=SID-1001";
String extractedSid = rewritten.substring(rewritten.indexOf(";jsessionid=") + ";jsessionid=".length());
Map<String, Object> trackAct = new LinkedHashMap<>();
trackAct.put("cookie_header", "JSESSIONID=SID-1001; Path=/; HttpOnly");
trackAct.put("hidden_input_name", mName.group(1));
trackAct.put("hidden_input_value", mVal.group(1));
trackAct.put("rewritten_url", rewritten);
trackAct.put("extracted_url_sid", extractedSid);
trackAct.put("page_session_false_directive", "<%@ page session=\"false\" %>");
addCase(cases, "session_tracking_mechanisms",
"核对 Cookie、隐藏表单域与 URL 重写三种会话跟踪载体及 page session=\"false\" 禁用语法。",
trackExp, trackAct);
// Case 2: Live loopback HttpServer JSESSIONID visit counter across 2 requests
final Map<String, SimulatedHttpSession> store = new LinkedHashMap<>();
final long[] clock = {1700000000000L, 1700000005000L};
final int[] reqSeq = {0};
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/session-demo", exchange -> {
long now = clock[Math.min(reqSeq[0], clock.length - 1)];
reqSeq[0]++;
String cookieHdr = exchange.getRequestHeaders().getFirst("Cookie");
String sid = null;
if (cookieHdr != null) {
for (String part : cookieHdr.split(";")) {
String trimmed = part.trim();
if (trimmed.startsWith("JSESSIONID=")) {
sid = trimmed.substring("JSESSIONID=".length());
}
}
}
SimulatedHttpSession sess = sid != null ? store.get(sid) : null;
if (sess == null || !sess.isValid()) {
sid = "SID-DEMO-01";
sess = new SimulatedHttpSession(sid, now);
store.put(sid, sess);
exchange.getResponseHeaders().add("Set-Cookie", "JSESSIONID=" + sid + "; Path=/; HttpOnly");
} else {
sess.touch(now);
}
String title;
Integer visitCount;
String userId;
if (sess.isNew()) {
title = "首次访问会话演示";
visitCount = 0;
userId = "USER-ABCD";
sess.setAttribute("userID", userId);
sess.setAttribute("visitCount", visitCount);
} else {
title = "再次访问会话演示";
Integer prev = (Integer) sess.getAttribute("visitCount");
visitCount = (prev == null ? 0 : prev) + 1;
userId = (String) sess.getAttribute("userID");
sess.setAttribute("visitCount", visitCount);
}
String body = "id=" + sess.getId()
+ "|isNew=" + sess.isNew()
+ "|title=" + title
+ "|userID=" + userId
+ "|visitCount=" + visitCount
+ "|created=" + sess.getCreationTime()
+ "|last=" + sess.getLastAccessedTime();
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
});
server.start();
String firstResp;
String secondResp;
String setCookieHeader;
try {
int port = server.getAddress().getPort();
URL url = new URL("http://127.0.0.1:" + port + "/session-demo");
HttpURLConnection c1 = (HttpURLConnection) url.openConnection();
c1.setRequestMethod("GET");
setCookieHeader = c1.getHeaderField("Set-Cookie");
firstResp = readAll(c1.getInputStream());
c1.disconnect();
String cookiePair = setCookieHeader.split(";")[0];
HttpURLConnection c2 = (HttpURLConnection) url.openConnection();
c2.setRequestMethod("GET");
c2.setRequestProperty("Cookie", cookiePair);
secondResp = readAll(c2.getInputStream());
c2.disconnect();
} finally {
server.stop(0);
}
Map<String, Object> httpExp = new LinkedHashMap<>();
httpExp.put("set_cookie", "JSESSIONID=SID-DEMO-01; Path=/; HttpOnly");
httpExp.put("first_visit", "id=SID-DEMO-01|isNew=true|title=首次访问会话演示|userID=USER-ABCD|visitCount=0|created=1700000000000|last=1700000000000");
httpExp.put("second_visit", "id=SID-DEMO-01|isNew=false|title=再次访问会话演示|userID=USER-ABCD|visitCount=1|created=1700000000000|last=1700000005000");
Map<String, Object> httpAct = new LinkedHashMap<>();
httpAct.put("set_cookie", setCookieHeader);
httpAct.put("first_visit", firstResp);
httpAct.put("second_visit", secondResp);
addCase(cases, "http_session_lifecycle_loopback",
"在本地环回 HttpServer 上验证首次建会话下发 JSESSIONID 与再次携带 Cookie 访问时 visitCount 自增及 lastAccessedTime 更新。",
httpExp, httpAct);
// Case 3: Attribute operations, enumeration, removal, timeout conversion, and invalidate
SimulatedHttpSession s = store.get("SID-DEMO-01");
s.setAttribute("role", "member");
List<String> attrNamesBefore = Collections.list(s.getAttributeNames());
s.removeAttribute("role");
Object afterRemove = s.getAttribute("role");
int defaultTimeoutSec = s.getMaxInactiveInterval();
int webXmlMinutes = 15;
s.setMaxInactiveInterval(webXmlMinutes * 60);
int configuredTimeoutSec = s.getMaxInactiveInterval();
s.invalidate();
boolean threwAfterInvalidate = false;
try {
s.getAttribute("userID");
} catch (IllegalStateException ex) {
threwAfterInvalidate = true;
}
Map<String, Object> opsExp = new LinkedHashMap<>();
List<String> expNames = new ArrayList<>();
expNames.add("userID");
expNames.add("visitCount");
expNames.add("role");
opsExp.put("attr_names_before_remove", expNames);
opsExp.put("removed_attr_value", null);
opsExp.put("default_timeout_seconds", 1800);
opsExp.put("web_xml_15min_in_seconds", 900);
opsExp.put("valid_after_invalidate", false);
opsExp.put("throws_illegal_state_after_invalidate", true);
Map<String, Object> opsAct = new LinkedHashMap<>();
opsAct.put("attr_names_before_remove", attrNamesBefore);
opsAct.put("removed_attr_value", afterRemove);
opsAct.put("default_timeout_seconds", defaultTimeoutSec);
opsAct.put("web_xml_15min_in_seconds", configuredTimeoutSec);
opsAct.put("valid_after_invalidate", s.isValid());
opsAct.put("throws_illegal_state_after_invalidate", threwAfterInvalidate);
addCase(cases, "session_attributes_timeout_and_invalidate",
"验证 getAttributeNames、removeAttribute、15 分钟 web.xml 超时换算为 900 秒以及 invalidate 后访问抛出 IllegalStateException。",
opsExp, opsAct);
Map<String, Object> root = new LinkedHashMap<>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
private static String readAll(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
}
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", Objects.equals(expected, actual));
cases.add(c);
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeString((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(",");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(",");
first = false;
sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeString(String.valueOf(obj));
}
private static String escapeString(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
else sb.append(ch);
}
}
return sb.append("\"").toString();
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
返回 900。因为 web.xml 的 <session-timeout> 单位是分钟,而 HttpSession.getMaxInactiveInterval() 与 setMaxInactiveInterval() 的单位都是秒(15 × 60 = 900)。