一、Session基本使用
服务端会话跟踪技术:将数据保存到服务端
JavaEE提供HttpSession接口,来实现一次会话的多次请求间数据共享功能
使用:
1、获取Session对象
HttpSession session = request.getSession();
2、Session对象功能:
void setAttribute(String name,Object o):存储数据到session域中
Object getAttribute(String name):根据key,获取值
void removeAttribute(String name):根据key,删除该键值对
代码示例:
ServletDemo1:
import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/demo1") public class ServletDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //存储到Session中 //1.获取Session对象 HttpSession session = request.getSession(); //2.存储数据 session.setAttribute("username","zs"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
ServletDemo2:
import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/demo2") public class ServletDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取数据,从session中 //1.获取Session对象 HttpSession session = request.getSession(); //2.获取数据 Object username = session.getAttribute("username"); System.out.println(username); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
访问demo1及demo2时控制台输出:
二、Session原理
Session是基于Cookie实现的
关闭浏览器后重新访问demo1的浏览器开发者工具显示:
重新访问demo2的浏览器开发者工具显示:
三、Session使用细节
Session钝化、活化:
钝化:在服务器正常关闭后,Tomcat会自动将Session数据写入硬盘的文件中
活化:再次启动服务器后,从文件中加载数据到Session中
Session销毁:
默认情况下,无操作,30分钟自动销毁
<session=config> <session-timeout>30</session-timeout> </session-config>
调用Session对象的invalidate()方法