Session - 用户会话
- Session(用户会话)用于保存与“浏览器窗口”对应的数据。
- Session的数据存储在Tomcat服务器的内存中,具有时效性。
- Session通过浏览器Cookie的SessionId值提取用户数据。
Session工作原理与特性
- Session默认时长为30分钟,存储在Tomcat服务器内存中。
- Session与浏览器窗口绑定,不同浏览器窗口间的存储空间相互隔离。
- Session创建后,会在Cookie中增加一个特殊的key名为session ID。
- Session ID作为身份标识,用于在服务器端提取对应的数据。
Session的应用场景
- 慕课网官网使用Session保存登录状态,实现跨请求的用户信息提取。
- Session适用于需要保持用户登录状态或跨请求传输数据的场景。
package com.imooc.servlet.session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;
@WebServlet("/session/random")
public class RandomServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer random = new Random().nextInt(10000);
HttpSession session = request.getSession();
session.setAttribute("random", random);
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h2>随机数" + random + "已生成</h2>");
}
}
package com.imooc.servlet.session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/session/show")
public class SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Integer random = (Integer) session.getAttribute("random");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("name=random的session值为:" + random);
}
}