Session life cycle and classic cases - preventing illegal access to the management page

Session life cycle and Session classic case - preventing illegal access to the management page

session life cycle

Session Lifecycle - Description

  1. public void setMaxInactiveInterval(int interval) Set the session timeout (in seconds), if the specified time exceeds, the session will be destroyed.

  2. When the value is positive, set the session timeout period.

  3. A negative number means never timeout

  4. public int getMaxInactiveInterval() Gets the session timeout

  5. public void invalidate() makes the current Session session invalid immediately

  6. If you do not call setMaxInactiveInterval() to specify the life span of the Session, Tomcat will take the default session time as the standard, and the default session timeout is 30 minutes, which can be set in tomcat's web.xml
    insert image description here

  7. The life cycle of Session refers to: the maximum interval between two requests from the client/browser, not the cumulative time. That is, when the client accesses its own session, the life cycle of the session will be recalculated from 0. (Interpretation: refers to the interval between two requests in the same session)

  8. Bottom layer: Tomcat uses a thread to poll the session status, and if the idle time of a session exceeds the set maximum value, the session will be destroyed

The code demo illustrates the life cycle of the Session

CreateCreateSession2

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);
    }
}

create-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);
    }
}

Interpretation of the Session life cycle

  1. Refers to the maximum interval between two visits to the session

  2. If you operate the session when the session has not expired, the calculation life cycle will be restarted

  3. Whether the session expires is maintained and managed by the server

  4. If we call invalidate(), the session will be deleted/destroyed directly

  5. If you want to delete an attribute of the session object, use removeAttribu(“xx”)

code example

Create 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 classic case - preventing illegal access to the management page

need

As long as the password is 666666, we think that the login is successful

Username is not limited

  1. If the verification is successful, enter the management page ManageServelt.java, otherwise enter error.html

  2. If the user accesses ManageServet.java directly, reset

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>

Guess you like

Origin blog.csdn.net/apple_67445472/article/details/131778631