> 文章列表 > Session使用和原理分析图与实现原理-- 代码演示说明 Session 的生命周期和读取的机制代码分析

Session使用和原理分析图与实现原理-- 代码演示说明 Session 的生命周期和读取的机制代码分析

Session使用和原理分析图与实现原理-- 代码演示说明 Session 的生命周期和读取的机制代码分析

目录

Web 开发会话技术 -Session

—session 技术

session 基本原理

Session 可以做什么

如何理解 Session

Session 的基本使用

session 底层实现机制

原理分析图

代码演示

CreateSession.java

测试 Session 创的机制, 注意抓包分析​编辑

ReadSession.java 

测试 Session 读取的机制, 注意抓包分析

Session 实现原理

 ​编辑

session 生命周期

Session 生命周期-说明

 代码演示说明 Session 的生命周期

CreateSession2

ReadSession2

Session 的生命周期

代码示例

DeleteSession

代码示例

需求

login.html

LoginCheckServlet

ManageServlet

error.html


Web 开发会话技术 -Session

—session 技术

  1. Session 是服务器端技术,服务器在运行时为每一个用户的浏览器创建一个其独享的 session 对象/
  2. 由于 session 为各个用户浏览器独享,所以用户在访问服务器的不同页面时,可以从各自 的 session 中读取/添加数据, 从而完成相应任务

session 基本原理

1. 当用户打开浏览器,访问某个网站, 操作 session 时,服务器就会在内存(在服务端)为该

浏览器分配一个 session 对象,该 session 对象被这个浏览器独占, 如图

2. 这个 session 对象也可看做是一个容器/集合,session 对象默认存在时间为 30min(这是在tomcat/conf/web.xml),也可修改

Session 可以做什么

1. 网上商城中的购物车

2. 保存登录用户的信息

3. 将数据放入到 Session 中,供用户在访问不同页面时,实现跨页面访问数据

4. 防止用户非法登录到某个页面

5. .....

如何理解 Session

1. session 存储结构示意图

2. 你可以把 session 看作是一容器类似 HashMap,有两列(K-V),每一行就是 session 的一个属性

3. 每个属性包含有两个部分,一个是该属性的名字(String),另外一个是它的值(Object)

Session 的基本使用

1. 创建和获取 Session,API 一样

HttpSession hs=request.getSession();

第 1 次调用是创建 Session 会话, 之后调用是获取创建好的 Session 对象

2. 向 session 添加属性

hs.setAttribute(String name,Object val);

3. 从 session 得到某个属性

Object obj=hs.getAttribute(String name)

4. 从 session 删除调某个属性:

hs.removeAttribute(String name);

5. isNew(); 判断是不是刚创建出来的 Session

6. 每个 Session 都有 1 个唯一标识 Id 值。通过 getId() 得到 Sessio

session 底层实现机制

原理分析图


 

代码演示

CreateSession.java

public class CreateSession extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//System.out.println("CreateSession 被调用...");//1. 获取session, 同时也可能创建sessionHttpSession session = request.getSession();//2. 给session获取idSystem.out.println("CreateSession 当前sessionid= " + session.getId());//3. 给session存放数据session.setAttribute("email", "zs@qq.com");//4. 给浏览器发送一个回复response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("<h1>创建/操作session成功...</h1>");writer.flush();writer.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

测试 Session 创的机制, 注意抓包分析

ReadSession.java 

public class ReadSession extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//System.out.println("ReadSession 被调用...");// 演示读取session//1. 获取session, 如果没有sesion, 也会创建HttpSession session = request.getSession();//输出sessionIdSystem.out.println("ReadSession sessionid= " + session.getId());//2. 读取属性Object email = session.getAttribute("email");if (email != null) {System.out.println("session属性 email= " + (String) email);} else {System.out.println("session中没有 email属性 ");}//给浏览器回复一下response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("<h1>读取session成功...</h1>");writer.flush();writer.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

测试 Session 读取的机制, 注意抓包分析

Session 实现原理

 

session 生命周期

Session 生命周期-说明

1. public void setMaxInactiveInterval(int interval) 设置 Session 的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。

2. 值为正数的时候,设定 Session 的超时时长。

3. 负数表示永不超时

4. public int getMaxInactiveInterval()获取 Session 的超时时间

5. public void invalidate() 让当前 Session 会话立即无效

6. 如果没有调用 setMaxInactiveInterval() 来指定 Session 的生命时长,Tomcat 会以 Session默认时长为准,Session 默认的超时为 30 分钟, 可以在 tomcat 的 web.xml 设置

7. Session 的生命周期指的是 :客户端/浏览器两次请求最大间隔时长,而不是累积时长。即当客户端访问了自己的 session,session 的生命周期将从 0 开始重新计算。(解读: 指的是同一个会话两次请求之间的间隔时间)

8. 底层: Tomcat 用一个线程来轮询会话状态,如果某个会话的空闲时间超过设定的最大值,则将该会话销毁

 代码演示说明 Session 的生命周期

CreateSession2

public class CreateSession2 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("CreateSession2 被调用");//创建sessionHttpSession session = request.getSession();System.out.println("CreateSession2 sid= " + session.getId());//设置生命周期为 60ssession.setMaxInactiveInterval(60);session.setAttribute("u", "jack");//回复一下浏览器response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("<h1>创建session成功, 设置生命周期60s</h1>");writer.flush();writer.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

ReadSession2

public class ReadSession2 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//System.out.println("ReadSession2 被调用...");//1. 获取到sessionHttpSession session = request.getSession();System.out.println("ReadSession2 sid= " + session.getId());//2. 读取session的属性Object u = session.getAttribute("u");if (u != null) {System.out.println("读取到session属性 u= " + (String) u);} else {System.out.println("读取不到session属性 u 说明原来的session被销毁");}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

Session 的生命周期

1) 指的是两次访问 session 的最大间隔时间
2) 如果你在 session 没有过期的情况下,操作 session, 则会重新开始计算生命周期
3) session 是否过期,是由服务器来维护和管理
4) 如我们调用了 invaliate() 会直接将该 session 删除/销毁
5) 如果希望删除 session 对象的某个属性, 使用 removeAttribu

代码示例

DeleteSession

public class DeleteSession extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("DeleteSession 被调用...");//演示如何删除sessionHttpSession session = request.getSession();session.invalidate();// 如果你要删除session的某个属性//session.removeAttribute("xxx");//回复一下浏览器response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("<h1>删除session成功</h1>");writer.flush();writer.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

代码示例

需求

只要密码为 666666, 我们认为就是登录成功
2) 用户名不限制
2. 如果验证成功,则进入管理页面 ManageServelt.java ,否则进入 error.html
3. 如果用户直接访问 ManageServet.java , 重定

login.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录页面</title>
</head>
<body>
<h1>用户登录界面</h1>
<form action="/cs/loginCheck" method="post">u:<input type="text" name="username"><br/>p:<input type="password" name="pwd"><br/><input type="submit" value="登录">
</form>
</body>
</html>

LoginCheckServlet

public class LoginCheckServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("LoginCheckServlet 被调用..");//功能-> 自己拆解 -> 逐步实现//1. 得到提交的用户名和密码String username = request.getParameter("username");String password = request.getParameter("password");if("666666".equals(password)) {//认为合法//把用户名保存到 sessionHttpSession session = request.getSession();session.setAttribute("loginuser", username);//请求转发到ManageServletrequest.getRequestDispatcher("/manage").forward(request, response);} else {//请求转发进入到 error.htmlrequest.getRequestDispatcher("/error.html").forward(request, response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

ManageServlet

public class ManageServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//判断该用户是否登录过HttpSession session = request.getSession();Object loginuser = session.getAttribute("loginuser");if(loginuser == null) {//说明该用户没有登录//重新登录-> 请求重定向//response.sendRedirect("/cs/userlogin.html");response.sendRedirect(request.getContextPath() + "/userlogin.html");return;} else {response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("<h1>用户管理页面</h1>");writer.println("欢迎你, 管理员:" + loginuser.toString());writer.flush();writer.close();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}

error.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录失败</title>
</head>
<body>
<h1>登录失败</h1>
<!--
web工程路径专题
1. a 标签是 浏览器解析
2. 第一 / 被解析成 http://localhost:8080/
3. 如果没有 / 会以当前浏览器地址栏 的 http://localhost:8080/工程路径../资源 去掉资源部分作为参考路径
-->
<a href="/cs/userlogin.html">点击重新登录</a>
</body>
</html>