Article Directory
- What is the use of Session
- Basic principles of Session
- Session common methods
- The underlying implementation mechanism of session
- Session life cycle
- Session classic case - preventing illegal access to the management page
- What is the use of Session
- Basic principles of Session
- Session common methods
- The underlying implementation mechanism of session
- Session life cycle
- Session classic case - preventing illegal access to the management page
What is the use of Session
Thinking about two questions—throwing bricks to attract jade
- 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?
- 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
-
Session is a server-side technology . The server creates an exclusive session object/collection for each user's browser at runtime.
-
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
- 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
- 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
What can a Session do?
- Shopping cart in the online store
- Save the information of the logged-in user
- Put the data into the Session for users to access data across pages when they visit different pages
- Prevent users from illegally logging in to a page
- …
How to understand Session
- Schematic diagram of session storage structure
- You can think of session as a container similar to HashMap, which has two columns (KV), and each row is an attribute of session.
- 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)
getAttribute(String name)
- Get the attribute value of the specified namesetAttribute(String name, Object value)
- Sets the property value for the specified nameremoveAttribute(String name)
- Remove the attribute value with the specified namegetId()
- get session idgetCreationTime()
- Get session creation timegetLastAccessedTime()
- Get session last access timesetMaxInactiveInterval(int interval)
- Set the maximum inactivity interval for a sessiongetMaxInactiveInterval()
- Get the maximum inactivity interval for a sessioninvalidate()
- invalidate sessionisNew()
- Determine if the session is newly created
Basic use of Session
-
Create and get session, same API
HttpSession hs = request.getSession()
The first call is to create a Session session, and the subsequent call is to obtain the created Session object -
Add attributes to session
hs.setAttribute(String name,Object val);
-
Get an attribute from session
Object obj=hs.getAttribute(String name);
-
Delete an attribute from the session
hs.removeAttribute(String name);
-
Judging whether it is a newly created Session
hs.isNew();
-
Get the session ID value of the session
hs.getId();
The underlying implementation mechanism of session
Principle analysis diagram (a picture is worth a thousand words)
There is a Session for each session.
getSession()
The method is the core of session creation, which is extremely important!
It first determines whether the browser has jsessionid
this cookie data:
- If not carried: create a session directly, and assign one
jsessionid
,jsessionid
and session management is maintained through a Map structure; - If carrying:
- If
id=jsessionid
the object does not exist: create a session and assign an id at the same time; - If there is
id=jsessionid
an object: just operate directly.
- If
Returns if the server created a session in this session Set-Cookie:jsessionid=xxx
.
Demonstration to create a session
-
Requirements: Demonstrate the underlying implementation mechanism of Session - create and read Session
-
create
CreateSession.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); } }
It is not carried when sending the request JsessionId
, and the server creates one for it after receiving itJsessionId
and return this in the response headerSet-Cookie: JESESSION=xxxxxxx
Then it JsessionId
is stored in the browser's cookie
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 JsessionId
corresponding session. And, neither does it return a response Set-Cookie: JESESSION=xxxxxxx
.
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);
}
}
Session realizes principle animation
How does the server implement a session to serve a user browser
Session life cycle
Session Lifecycle - Description
public void setMaxInactiveInterval(int interval)
Set the session timeout (in seconds), and the session will be destroyed if the specified time is exceeded.- When the value is positive, set the session timeout period.
- A negative number means never timeout
public int getMaxInactiveInterval()
Get the session timeoutpublic void invalidate()
Make the current Session invalid immediately- 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
- 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)
- 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);
}
}
Interpretation: Session life cycle
- Refers to the maximum interval between two visits to the session
- If you operate the session when the session has not expired, the calculation life cycle will be restarted
- Whether the session expires is maintained and managed by the server
- If we call it,
invaliate()
the session will be deleted/destroyed directly- If you want to delete an attribute of the session object, use
removeAttribute("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)
-
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 entererror.html
- If the user visits directly
ManageServet.java
, redirect touserlogin.html
- As long as the password is
Commentary
-
create
userlogin.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>
-
create
LoginCheckServlet.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); } }
-
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
- Basic principles of Session
- Session common methods
- The underlying implementation mechanism of session
- Session life cycle
- Session classic case - preventing illegal access to the management page
- What is the use of Session
- Basic principles of Session
- Session common methods
- The underlying implementation mechanism of session
- Session life cycle
- Session classic case - preventing illegal access to the management page
What is the use of Session
Thinking about two questions—throwing bricks to attract jade
- 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?
- 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
-
Session is a server-side technology . The server creates an exclusive session object/collection for each user's browser at runtime.
-
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
- 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
- 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
What can a Session do?
- Shopping cart in the online store
- Save the information of the logged-in user
- Put the data into the Session for users to access data across pages when they visit different pages
- Prevent users from illegally logging in to a page
- …
How to understand Session
- Schematic diagram of session storage structure
- You can think of session as a container similar to HashMap, which has two columns (KV), and each row is an attribute of session.
- 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)
getAttribute(String name)
- Get the attribute value of the specified namesetAttribute(String name, Object value)
- Sets the property value for the specified nameremoveAttribute(String name)
- Remove the attribute value with the specified namegetId()
- get session idgetCreationTime()
- Get session creation timegetLastAccessedTime()
- Get session last access timesetMaxInactiveInterval(int interval)
- Set the maximum inactivity interval for a sessiongetMaxInactiveInterval()
- Get the maximum inactivity interval for a sessioninvalidate()
- invalidate sessionisNew()
- Determine if the session is newly created
Basic use of Session
-
Create and get session, same API
HttpSession hs = request.getSession()
The first call is to create a Session session, and the subsequent call is to obtain the created Session object -
Add attributes to session
hs.setAttribute(String name,Object val);
-
Get an attribute from session
Object obj=hs.getAttribute(String name);
-
Delete an attribute from the session
hs.removeAttribute(String name);
-
Judging whether it is a newly created Session
hs.isNew();
-
Get the session ID value of the session
hs.getId();
The underlying implementation mechanism of session
Principle analysis diagram (a picture is worth a thousand words)
There is a Session for each session.
getSession()
The method is the core of session creation, which is extremely important!
It first determines whether the browser has jsessionid
this cookie data:
- If not carried: create a session directly, and assign one
jsessionid
,jsessionid
and session management is maintained through a Map structure; - If carrying:
- If
id=jsessionid
the object does not exist: create a session and assign an id at the same time; - If there is
id=jsessionid
an object: just operate directly.
- If
Returns if the server created a session in this session Set-Cookie:jsessionid=xxx
.
Demonstration to create a session
-
Requirements: Demonstrate the underlying implementation mechanism of Session - create and read Session
-
create
CreateSession.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); } }
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
Then it JsessionId
is stored in the browser's cookie
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 JsessionId
corresponding 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);
}
}
Session realizes principle animation
How does the server implement a session to serve a user browser
Session life cycle
Session Lifecycle - Description
public void setMaxInactiveInterval(int interval)
Set the session timeout (in seconds), and the session will be destroyed if the specified time is exceeded.- When the value is positive, set the session timeout period.
- A negative number means never timeout
public int getMaxInactiveInterval()
Get the session timeoutpublic void invalidate()
Make the current Session invalid immediately- 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
- 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)
- 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);
}
}
Interpretation: Session life cycle
- Refers to the maximum interval between two visits to the session
- If you operate the session when the session has not expired, the calculation life cycle will be restarted
- Whether the session expires is maintained and managed by the server
- If we call it,
invaliate()
the session will be deleted/destroyed directly- If you want to delete an attribute of the session object, use
removeAttribute("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)
-
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 entererror.html
- If the user visits directly
ManageServet.java
, redirect touserlogin.html
- As long as the password is
Commentary
-
create
userlogin.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>
-
create
LoginCheckServlet.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); } }
-
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); } }