HttpSession 介绍

  • HttpSession: 服务器端会话管理技术
    本质上也是采用客户端会话管理技术
    只不过在客户端保存的是一个特殊标识,而且共享的数据保存到了服务器端的内存对象中
    每次请求时,会将特殊标识带到服务器端,根据这个表示来找到对应的内存空间,从而实现数据共享
    是Servlet规范中四大域对象之一的会话域对象
  • 作用: 可以实现数据共享

  • 8- Cookie&Session&JSP -Session_用户名

  • image.png

HttpSession 常用方法





8- Cookie&Session&JSP -Session_共享数据_02


image.png


HttpSession 获取

  • HttpSession 实现类对象是通过HttpServletRequest 对象来获取

  • 8- Cookie&Session&JSP -Session_共享数据_03

  • image.png


  • 8- Cookie&Session&JSP -Session_序列化_04

  • 获取Session的两个方法.png

HttpSession 使用

  • 需求说明
    通过第一个Servlet 设置共享数据用户名,并在第二个Servlet获取到
  • 最终目的
    掌握HttpSession 的基本使用,如何获取和使用
  • 实现步骤
    1. 在第一个Servlet 中获取请求的用户名
    2. 获取SerlvetSession对象
    3. 将用户名设置到共享数据中
    4. 在第二个 Servlet 中获取HttpSession对象
    5. 获取共享数据用户名
    6. 将获取到用户名响应给客户端

实现代码1:

/*
Session 的基本使用
* */
@WebServlet("/servletSession1")
public class servletSession extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取请求的用户名 访问时自己拼接username参数
String username = req.getParameter("username");
//2. 获取HttpSession对象
HttpSession session = req.getSession();

//这两条输出语句是验证session是不是一样的
System.out.println(session);
System.out.println(session.getId());
//3. 将用户名设置到共享数据中
session.setAttribute("username",username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);
}
}

实现代码2:

/*
Session 的基本使用
* */
@WebServlet("/servletSession2")
public class servletSession2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取HttpSession 对象
HttpSession session = req.getSession();

//这两条输出语句是验证session是不是一样的
System.out.println(session);
System.out.println(session.getId());
//获取共享数据
Object username = session.getAttribute("username");
//将数据响应给浏览器
resp.getWriter().write(username + "");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}



访问测试




8- Cookie&Session&JSP -Session_用户名_05


image.png


HttpSession 细节

  • 唯一标识的查看

  • 8- Cookie&Session&JSP -Session_共享数据_06

  • image.png
  • 浏览器禁用Cookie 访问的Session不同
  • 1. 方式一: 通过提示信息告知用户,大部分网站采用的解决方式(推荐)
  • 2. 方式二: 访问时拼接jsessionid表示,通过encodeURL()方法重写地址(了解)

  • 8- Cookie&Session&JSP -Session_用户名_07

  • image.png

钝化和活化

  • 什么是钝化和活化
    钝化: 序列化,把长时间不用, 但还不到过期时间的HttpSession进行序列化,写道磁盘上
    活化: 相反的状态
  • 何时钝化
    第一种情况:
    a: 当访问量很大时,服务器会根据getLastaccessTime 来进行排序;
    b: 对长时间不用,但是还没有到过期时间的HttpSession进行序列化
    第二种情况: 当服务进行重启的时候,为了保持客户HttpSession 中的数据,也要对其进行序列化
  • 注意
    HttpSession 的序列化由服务器自动完成,我们无需关心