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 被调用");
        //创建session
        HttpSession session = request.getSession();
        System.out.println("CreateSession2 sid= " + session.getId());
        //设置生命周期为 60s
        session.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. 获取到session
        HttpSession 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(“xx”)

代码示例

创建DeleteSession

public class DeleteSession extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("DeleteSession 被调用...");
        //演示如何删除session
        HttpSession 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);
    }
}

Session 经典案例-防止非法进入管理页面

需求

只要密码为 666666, 我们认为就是登录成功

用户名不限制

  1. 如果验证成功,则进入管理页面 ManageServelt.java ,否则进入 error.html
  2. 如果用户直接访问 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)) {//认为合法
            //把用户名保存到 session
            HttpSession session = request.getSession();
            session.setAttribute("loginuser", username);
            //请求转发到ManageServlet
            request.getRequestDispatcher("/manage").forward(request, response);
        } else {
            //请求转发进入到 error.html
            request.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>


目录
相关文章
|
安全 Java 应用服务中间件
组件漏洞修复---修改SpringBoot内置tomcat的版本号
安全反应Tomcat9.0.41存在安全漏洞,让将所有服务的Tomcat版本升级到9.0.44,我们都知道SpingBoot中是集成的有内置的Tomcat的,叫Embed-Tomcat,这个Tomcat和我们用于部署war包的Tomcat还是有有一些区别的,但是版本一直和Tomcat基本保持一致。
4092 0
组件漏洞修复---修改SpringBoot内置tomcat的版本号
|
JSON 数据格式
net.sf.json.JSONObject 和org.json.JSONObject 的差别
net.sf.json.JSONObject 和org.json.JSONObject 的差别
|
缓存 前端开发 Java
【二十八】springboot之通过threadLocal+参数解析器实现同session一样保存当前登录信息的功能
【二十八】springboot之通过threadLocal+参数解析器实现同session一样保存当前登录信息的功能
688 1
|
7月前
|
存储 弹性计算 缓存
阿里云服务器通用算力型u1、u2i、u2a有何区别?实例性能、适用场景及选购指南参考
阿里云通用算力型U实例包含u1、u2i和u2a三款云服务器,均具均衡资源配置和高性价比,但各有差异。u1是经典款,以稳定性和成本效益为优势,适合预算有限且对稳定性有要求的中小企业;u2i是新一代Intel平台实例,算力与I/O性能显著提升,适合对性能有更高要求的企业级应用;u2a则采用AMD平台,追求极致性价比,适合对成本敏感且追求高性能的用户。用户可根据需求和预算选择。
|
10月前
阿里云盘企业版收费标准价格表——用户数、存储空间配置详单
阿里云盘企业版CDE全新上线,首月免费试用,最高节省87%费用。提供5人至100人多种配置,5人200GB仅6.63元/月,20人2TB低至749元/年,较老版降幅达85.3%。支持灵活升配,性价比大幅提升。
1689 0
|
弹性计算 JavaScript Ubuntu
WebSocket协议相关的测试命令工具使用简介
本文介绍了针对WebSocket的测试工具wscat和websocat的基本使用方法,以及通过curl命令测试HTTP/HTTPS协议的方式。对于WebSocket,直接使用curl测试较为复杂,推荐使用wscat或websocat。文中详细说明了这两种工具的安装步骤、常用参数及连接示例,例如在ECS上开启8080端口监听并进行消息收发测试。此外,还提供了curl命令的手动设置头部信息以模拟WebSocket握手的示例,但指出curl仅能作为客户端测试工具,无法模拟服务器。
4594 5
|
安全 Cloud Native 容灾
海外泼天流量|浅谈全球化技术架构
本文对海外泼天流量现状做了快速整理,旨在抛砖引玉,促进国内企业在出海过程中,交流如何构建全球化技术架构的落地经验,相信会有越来越多资深人士分享更深层次的实践。
994 51
|
监控 网络协议 应用服务中间件
动图图解!收到RST,就一定会断开TCP连接吗?
动图图解!收到RST,就一定会断开TCP连接吗?
1441 0
|
XML Java Kotlin
springboot + minio + kkfile实现文件预览
本文介绍了如何在容器中安装和启动kkfileviewer,并通过Spring Boot集成MinIO实现文件上传与预览功能。首先,通过下载kkfileviewer源码并构建Docker镜像来部署文件预览服务。接着,在Spring Boot项目中添加MinIO依赖,配置MinIO客户端,并实现文件上传与获取预览链接的接口。最后,通过测试验证文件上传和预览功能的正确性。
2110 4
springboot + minio + kkfile实现文件预览
|
数据采集 机器学习/深度学习 搜索推荐
大数据与社交媒体:用户行为分析
【10月更文挑战第31天】在数字化时代,社交媒体成为人们生活的重要部分,大数据技术的发展使其用户行为分析成为企业理解用户需求、优化产品设计和提升用户体验的关键手段。本文探讨了大数据在社交媒体用户行为分析中的应用,包括用户画像构建、情感分析、行为路径分析和社交网络分析,以及面临的挑战与机遇。
1441 3