【JavaWeb】Session Detailed Explanation + Underlying Analysis + Code Demonstration

Article Directory

What is the use of Session

Thinking about two questions—throwing bricks to attract jade

  1. After different users log in to the website, no matter which page of the website the user browses, the name of the login person can be displayed, and they can also check the products in their shopping cart at any time. How is this achieved?
  1. That is to say, when a user browses different pages of the website, how does the server know whether Zhang San is browsing this page or Li Si is browsing this page?

The solution—session technology

  1. Session is a server-side technology . The server creates an exclusive session object/collection for each user's browser at runtime.

  2. Since the session is exclusive to each user's browser , when the user visits different pages of the server, they can read/add data from their respective sessions to complete corresponding tasks.

Basic principles of Session

Schematic diagram of Sesson principle

image-20230311125917379

image-20230311125929010

  1. When a user opens a browser, visits a website, and operates a session, the server will allocate a session object to the browser in memory (on the server side), and the session object is exclusively occupied by the browser, as shown in the figure
  2. This session object can also be regarded as a container/collection. The default existence time of the session object is 30 minutes (this is in tomcat/conf/web.xml), and it can also be modified
    image-20230311131023482
    image-20230311131117583

What can a Session do?

  1. Shopping cart in the online store
  2. Save the information of the logged-in user
  3. Put the data into the Session for users to access data across pages when they visit different pages
  4. Prevent users from illegally logging in to a page

How to understand Session

  1. Schematic diagram of session storage structure
    image-20230311130755315
  2. You can think of session as a container similar to HashMap, which has two columns (KV), and each row is an attribute of session.
  3. Each attribute contains two parts, one is the name of the attribute (String), and the other is its value (Object)

Session common methods

Session document

HttpSession (Java™ EE 7 Specification APIs) (oracle.com)

  1. getAttribute(String name)- Get the attribute value of the specified name
  2. setAttribute(String name, Object value)- Sets the property value for the specified name
  3. removeAttribute(String name)- Remove the attribute value with the specified name
  4. getId()- get session id
  5. getCreationTime()- Get session creation time
  6. getLastAccessedTime()- Get session last access time
  7. setMaxInactiveInterval(int interval)- Set the maximum inactivity interval for a session
  8. getMaxInactiveInterval()- Get the maximum inactivity interval for a session
  9. invalidate()- invalidate session
  10. isNew()- Determine if the session is newly created

Basic use of Session

  1. Create and get session, same API

    HttpSession hs = request.getSession()
    

    image-20230311132419601
    The first call is to create a Session session, and the subsequent call is to obtain the created Session object

  2. Add attributes to session

    hs.setAttribute(String name,Object val);
    

    image-20230311133251959

  3. Get an attribute from session

    Object obj=hs.getAttribute(String name);
    

    image-20230311133334589

  4. Delete an attribute from the session

    hs.removeAttribute(String name);
    

    image-20230311133148068

  5. Judging whether it is a newly created Session

    hs.isNew();
    

    image-20230311133037443

  6. Get the session ID value of the session

    hs.getId();
    

    image-20230311133444206

The underlying implementation mechanism of session

Principle analysis diagram (a picture is worth a thousand words)

image-20230311134730119

There is a Session for each session.

image-20230311134817009

getSession()The method is the core of session creation, which is extremely important!

It first determines whether the browser has jsessionidthis cookie data:

  1. If not carried: create a session directly, and assign one jsessionid, jsessionidand session management is maintained through a Map structure;
  2. If carrying:
    1. If id=jsessionidthe object does not exist: create a session and assign an id at the same time;
    2. If there is id=jsessionidan object: just operate directly.

Returns if the server created a session in this session Set-Cookie:jsessionid=xxx.

Demonstration to create a session

  1. Requirements: Demonstrate the underlying implementation mechanism of Session - create and read Session

  2. createCreateSession.java

    package com.hspedu.session;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * @ClassName CreateSession
     * @Description 演示Session的创建
     * @Author zephyr
     * @Date 2023/3/11 14:16
     * @Version 1.0
     */
    
    @WebServlet(name = "CreateSession", value = "/createSession")
    public class CreateSession extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            System.out.println("================CreateSession 被调用================");
    
            //1. 获取session,同时也可能创建session
            HttpSession session = request.getSession();
            //2. 获取sessionId
            System.out.println("当前sessionId = " + session.getId());
            //3. 给session存放数据
            session.setAttribute("email", "[email protected]");
    
            //4. 给浏览器发送回复
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<h1>创建Session成功</h1>");
            writer.flush();
            writer.close();
    
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    
    

    image-20230311144451043

It is not carried when sending the request JsessionId, and the server creates one for it after receiving itJsessionId

image-20230311144608335

and return this in the response headerSet-Cookie: JESESSION=xxxxxxx

image-20230311144644024

Then it JsessionIdis stored in the browser's cookie

image-20230311150014293


Now if we initiate a request to the client again and carry the one just now JsessionId, then the client will no longer create a new session for us, but use the JsessionIdcorresponding session. And, neither does it return a response Set-Cookie: JESESSION=xxxxxxx.

image-20230311150513169

Demo read session

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName ReadSession
 * @Description 演示读取session
 * @Author zephyr
 * @Date 2023/3/11 15:10
 * @Version 1.0
 */

@WebServlet(name = "ReadSession", value = "/readSession")
public class ReadSession extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================ReadSession 被调用================");
        //1. 获取Session,如果没有session也会创建
        HttpSession session = request.getSession();
        //输出sessionId
        System.out.println("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();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

image-20230311152040016

image-20230311152058821

image-20230311152021201

Session realizes principle animation

How does the server implement a session to serve a user browser

image-20230311152248702

Session life cycle

Session Lifecycle - Description

  1. public void setMaxInactiveInterval(int interval)Set the session timeout (in seconds), and the session will be destroyed if the specified time is exceeded.
    1. When the value is positive, set the session timeout period.
    2. A negative number means never timeout
  2. public int getMaxInactiveInterval()Get the session timeout
  3. public void invalidate()Make the current Session invalid immediately
  4. If there is no 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

image-20230311131117583

  1. 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)
  2. 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

Session life cycle - application instance

  • Requirements: Code demonstration to illustrate the life cycle of Session

createSession2.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName CreateSession2
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 15:35
 * @Version 1.0
 */

@WebServlet(name = "CreateSession2", value = "/createSession2")
public class CreateSession2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================CreateSession2 被调用================");

        //获取Session,如果没有session也会创建
        HttpSession session = request.getSession();
        //输出session的id
        System.out.println("sessionId = " + session.getId());
        //设置生命周期为60s
        session.setMaxInactiveInterval(60);
        //设置两个属性
        session.setAttribute("u", "zephyr666");

        //给浏览器发送回复
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>创建session成功,生命周期60s</h1>");
        writer.flush();
        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

ReadSession2.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;

/**
 * @ClassName ReadSession2
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 15:37
 * @Version 1.0
 */

@WebServlet(name = "ReadSession2", value = "/readSession2")
public class ReadSession2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================ReadSession2 被调用================");
        //获取Session
        HttpSession session = request.getSession();
        //输出session的id
        System.out.println("sessionId = " + session.getId());
        //获取session的属性
        Object u = session.getAttribute("u");
        if (u != null){
    
    
            System.out.println("u = " + u);
        } else {
    
    
            System.out.println("读取不到session属性u");
        }

        //给浏览器回回复
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>读取session成功</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

image-20230311155110040

Interpretation: 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 it, invaliate()the session will be deleted/destroyed directly
  5. If you want to delete an attribute of the session object, useremoveAttribute("xx")

DeleteSession.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * @ClassName DeleteSession
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 17:26
 * @Version 1.0
 */

@WebServlet(name = "DeleteSession", value = "/DeleteSession")
public class DeleteSession extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        HttpSession session = request.getSession();
        // 让 Session 会话立即超时
        session.invalidate();

        response.setContentType("text/html;charset=utf-8"); // 先获取 Session 对象
        response.getWriter().write("Session 已经设置为超时");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

Session classic case - preventing illegal access to the management page

assignment

  • Requirement Description: Complete the application case of preventing users from logging in to the management page (as shown in the figure)
    image-20230312000247733

  • illustrate:

    • As long as the password is 666666, we consider it a successful login
    • Username is not limited
    • If the verification is successful, enter the management page ManageServelt.java, otherwise enter error.html
    • If the user visits directly ManageServet.java, redirect touserlogin.html

Commentary

  1. createuserlogin.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>用户登录</title></head>
    <body>
    <h1>用户登录</h1>
    <form action="/cs/loginCheck"
          method="post">
      用户名:<input type="text" name="username"/><br/><br/>
      密 码:<input type="password" name="password"><br><br/>
      <input type="submit" value="登录"></form>
    </body>
    </html>
    
  2. createLoginCheckServlet.java

    package com.hspedu.session.homework;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    /**
     * @ClassName LoginCheckServlet
     * @Description 检测用户名和密码是否正确,正确则跳转到manage页面,错误则返回error.html
     * @Author zephyr
     * @Date 2023/3/13 11:12
     * @Version 1.0
     */
    
    @WebServlet(name = "LoginCheckServlet", value = "/loginCheck")
    public class LoginCheckServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(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);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    
  3. ManageServlet.java

    package com.hspedu.session.homework;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * @ClassName ManageServlet
     * @Description 管理员页面。通过session,如果已经登录过就可以直接访问,如果没有登陆过则重定向到登录页面。
     * @Author zephyr
     * @Date 2023/3/13 11:15
     * @Version 1.0
     */
    
    @WebServlet(name = "ManageServlet", value = "/manage")
    public class ManageServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            System.out.println("================ManageServlet 被调用================");
    
            //判断该用户是否登陆过
            HttpSession session = request.getSession();
            Object loginuser = session.getAttribute("loginuser");
            if (loginuser == null){
          
          
                //重新登陆
                response.sendRedirect(request.getContextPath() + "/userlogin.html");
            } else {
          
          
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.println("<h1>用户管理页面</h1>");
                writer.println("欢迎你,管理员: " + loginuser.toString());
                writer.flush();
                writer.close();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    

Article Directory

What is the use of Session

Thinking about two questions—throwing bricks to attract jade

  1. After different users log in to the website, no matter which page of the website the user browses, the name of the login person can be displayed, and they can also check the products in their shopping cart at any time. How is this achieved?
  1. That is to say, when a user browses different pages of the website, how does the server know whether Zhang San is browsing this page or Li Si is browsing this page?

The solution—session technology

  1. Session is a server-side technology . The server creates an exclusive session object/collection for each user's browser at runtime.

  2. Since the session is exclusive to each user's browser , when the user visits different pages of the server, they can read/add data from their respective sessions to complete corresponding tasks.

Basic principles of Session

Schematic diagram of Sesson principle

image-20230311125917379

image-20230311125929010

  1. When a user opens a browser, visits a website, and operates a session, the server will allocate a session object to the browser in memory (on the server side), and the session object is exclusively occupied by the browser, as shown in the figure
  2. This session object can also be regarded as a container/collection. The default existence time of the session object is 30 minutes (this is in tomcat/conf/web.xml), and it can also be modified
    image-20230311131023482
    image-20230311131117583

What can a Session do?

  1. Shopping cart in the online store
  2. Save the information of the logged-in user
  3. Put the data into the Session for users to access data across pages when they visit different pages
  4. Prevent users from illegally logging in to a page

How to understand Session

  1. Schematic diagram of session storage structure
    image-20230311130755315
  2. You can think of session as a container similar to HashMap, which has two columns (KV), and each row is an attribute of session.
  3. Each attribute contains two parts, one is the name of the attribute (String), and the other is its value (Object)

Session common methods

Session document

HttpSession (Java™ EE 7 Specification APIs) (oracle.com)

  1. getAttribute(String name)- Get the attribute value of the specified name
  2. setAttribute(String name, Object value)- Sets the property value for the specified name
  3. removeAttribute(String name)- Remove the attribute value with the specified name
  4. getId()- get session id
  5. getCreationTime()- Get session creation time
  6. getLastAccessedTime()- Get session last access time
  7. setMaxInactiveInterval(int interval)- Set the maximum inactivity interval for a session
  8. getMaxInactiveInterval()- Get the maximum inactivity interval for a session
  9. invalidate()- invalidate session
  10. isNew()- Determine if the session is newly created

Basic use of Session

  1. Create and get session, same API

    HttpSession hs = request.getSession()
    

    image-20230311132419601
    The first call is to create a Session session, and the subsequent call is to obtain the created Session object

  2. Add attributes to session

    hs.setAttribute(String name,Object val);
    

    image-20230311133251959

  3. Get an attribute from session

    Object obj=hs.getAttribute(String name);
    

    image-20230311133334589

  4. Delete an attribute from the session

    hs.removeAttribute(String name);
    

    image-20230311133148068

  5. Judging whether it is a newly created Session

    hs.isNew();
    

    image-20230311133037443

  6. Get the session ID value of the session

    hs.getId();
    

    image-20230311133444206

The underlying implementation mechanism of session

Principle analysis diagram (a picture is worth a thousand words)

image-20230311134730119

There is a Session for each session.

image-20230311134817009

getSession()The method is the core of session creation, which is extremely important!

It first determines whether the browser has jsessionidthis cookie data:

  1. If not carried: create a session directly, and assign one jsessionid, jsessionidand session management is maintained through a Map structure;
  2. If carrying:
    1. If id=jsessionidthe object does not exist: create a session and assign an id at the same time;
    2. If there is id=jsessionidan object: just operate directly.

Returns if the server created a session in this session Set-Cookie:jsessionid=xxx.

Demonstration to create a session

  1. Requirements: Demonstrate the underlying implementation mechanism of Session - create and read Session

  2. createCreateSession.java

    package com.hspedu.session;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * @ClassName CreateSession
     * @Description 演示Session的创建
     * @Author zephyr
     * @Date 2023/3/11 14:16
     * @Version 1.0
     */
    
    @WebServlet(name = "CreateSession", value = "/createSession")
    public class CreateSession extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            System.out.println("================CreateSession 被调用================");
    
            //1. 获取session,同时也可能创建session
            HttpSession session = request.getSession();
            //2. 获取sessionId
            System.out.println("当前sessionId = " + session.getId());
            //3. 给session存放数据
            session.setAttribute("email", "[email protected]");
    
            //4. 给浏览器发送回复
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<h1>创建Session成功</h1>");
            writer.flush();
            writer.close();
    
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    
    

    image-20230311144451043

It is not carried when sending the request JsessionId, and the server creates one for it after receiving itJsessionId

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-rJQKggQL-1678685554206)(https://img.jing10.top/uPic/20230311image-20230311144608335.png)]

and return this in the response headerSet-Cookie: JESESSION=xxxxxxx

image-20230311144644024

Then it JsessionIdis stored in the browser's cookie

image-20230311150014293


Now if we initiate a request to the client again and carry the one just now JsessionId, then the client will no longer create a new session for us, but use the JsessionIdcorresponding session. And, neither does it return a response Set-Cookie: JESESSION=xxxxxxx.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hjBNVb0C-1678685554207)(https://img.jing10.top/uPic/20230311image-20230311150513169.png)]

Demo read session

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName ReadSession
 * @Description 演示读取session
 * @Author zephyr
 * @Date 2023/3/11 15:10
 * @Version 1.0
 */

@WebServlet(name = "ReadSession", value = "/readSession")
public class ReadSession extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================ReadSession 被调用================");
        //1. 获取Session,如果没有session也会创建
        HttpSession session = request.getSession();
        //输出sessionId
        System.out.println("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();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

image-20230311152040016

image-20230311152058821

image-20230311152021201

Session realizes principle animation

How does the server implement a session to serve a user browser

image-20230311152248702

Session life cycle

Session Lifecycle - Description

  1. public void setMaxInactiveInterval(int interval)Set the session timeout (in seconds), and the session will be destroyed if the specified time is exceeded.
    1. When the value is positive, set the session timeout period.
    2. A negative number means never timeout
  2. public int getMaxInactiveInterval()Get the session timeout
  3. public void invalidate()Make the current Session invalid immediately
  4. If there is no 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

image-20230311131117583

  1. 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)
  2. 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

Session life cycle - application instance

  • Requirements: Code demonstration to illustrate the life cycle of Session

createSession2.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName CreateSession2
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 15:35
 * @Version 1.0
 */

@WebServlet(name = "CreateSession2", value = "/createSession2")
public class CreateSession2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================CreateSession2 被调用================");

        //获取Session,如果没有session也会创建
        HttpSession session = request.getSession();
        //输出session的id
        System.out.println("sessionId = " + session.getId());
        //设置生命周期为60s
        session.setMaxInactiveInterval(60);
        //设置两个属性
        session.setAttribute("u", "zephyr666");

        //给浏览器发送回复
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>创建session成功,生命周期60s</h1>");
        writer.flush();
        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

ReadSession2.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;

/**
 * @ClassName ReadSession2
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 15:37
 * @Version 1.0
 */

@WebServlet(name = "ReadSession2", value = "/readSession2")
public class ReadSession2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("================ReadSession2 被调用================");
        //获取Session
        HttpSession session = request.getSession();
        //输出session的id
        System.out.println("sessionId = " + session.getId());
        //获取session的属性
        Object u = session.getAttribute("u");
        if (u != null){
    
    
            System.out.println("u = " + u);
        } else {
    
    
            System.out.println("读取不到session属性u");
        }

        //给浏览器回回复
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>读取session成功</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

image-20230311155110040

Interpretation: 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 it, invaliate()the session will be deleted/destroyed directly
  5. If you want to delete an attribute of the session object, useremoveAttribute("xx")

DeleteSession.java

package com.hspedu.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * @ClassName DeleteSession
 * @Description TODO
 * @Author zephyr
 * @Date 2023/3/11 17:26
 * @Version 1.0
 */

@WebServlet(name = "DeleteSession", value = "/DeleteSession")
public class DeleteSession extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        HttpSession session = request.getSession();
        // 让 Session 会话立即超时
        session.invalidate();

        response.setContentType("text/html;charset=utf-8"); // 先获取 Session 对象
        response.getWriter().write("Session 已经设置为超时");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
}

Session classic case - preventing illegal access to the management page

assignment

  • Requirement Description: Complete the application case of preventing users from logging in to the management page (as shown in the figure)
    image-20230312000247733

  • illustrate:

    • As long as the password is 666666, we consider it a successful login
    • Username is not limited
    • If the verification is successful, enter the management page ManageServelt.java, otherwise enter error.html
    • If the user visits directly ManageServet.java, redirect touserlogin.html

Commentary

  1. createuserlogin.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>用户登录</title></head>
    <body>
    <h1>用户登录</h1>
    <form action="/cs/loginCheck"
          method="post">
      用户名:<input type="text" name="username"/><br/><br/>
      密 码:<input type="password" name="password"><br><br/>
      <input type="submit" value="登录"></form>
    </body>
    </html>
    
  2. createLoginCheckServlet.java

    package com.hspedu.session.homework;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    /**
     * @ClassName LoginCheckServlet
     * @Description 检测用户名和密码是否正确,正确则跳转到manage页面,错误则返回error.html
     * @Author zephyr
     * @Date 2023/3/13 11:12
     * @Version 1.0
     */
    
    @WebServlet(name = "LoginCheckServlet", value = "/loginCheck")
    public class LoginCheckServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(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);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    
  3. ManageServlet.java

    package com.hspedu.session.homework;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * @ClassName ManageServlet
     * @Description 管理员页面。通过session,如果已经登录过就可以直接访问,如果没有登陆过则重定向到登录页面。
     * @Author zephyr
     * @Date 2023/3/13 11:15
     * @Version 1.0
     */
    
    @WebServlet(name = "ManageServlet", value = "/manage")
    public class ManageServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            System.out.println("================ManageServlet 被调用================");
    
            //判断该用户是否登陆过
            HttpSession session = request.getSession();
            Object loginuser = session.getAttribute("loginuser");
            if (loginuser == null){
          
          
                //重新登陆
                response.sendRedirect(request.getContextPath() + "/userlogin.html");
            } else {
          
          
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.println("<h1>用户管理页面</h1>");
                writer.println("欢迎你,管理员: " + loginuser.toString());
                writer.flush();
                writer.close();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
            doGet(request, response);
        }
    }
    

Guess you like

Origin blog.csdn.net/weixin_46421722/article/details/129492205