You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
text1/src/web/servlet/login/LogoutServlet.java

51 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package web.servlet.login;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
// 使用WebServlet注解将该类映射到"/logoutServlet"这个URL路径表明这是一个用于处理对应网络请求的Servlet类
// 从类名可以推断出其主要功能是处理用户注销相关的业务逻辑。
@WebServlet("/logoutServlet")
public class LogoutServlet extends HttpServlet {
// 重写doPost方法用于处理HTTP POST请求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求的字符编码为"UTF-8",确保能正确解析包含中文等多字节字符的请求参数(虽然此处可能没有特别涉及中文相关参数,但保持良好的编码设置习惯是必要的)。
request.setCharacterEncoding("UTF-8");
// 获取当前请求对应的HttpSession对象HttpSession用于在多个请求之间保存用户相关的会话信息
// 在这里主要是为了操作会话中存储的用户登录相关的属性信息,以便实现注销功能。
HttpSession session = request.getSession();
// 从会话中移除名为"student"的属性,该属性通常在用户(学生角色)登录成功后被设置,用于标识当前登录的学生用户信息,
// 移除它意味着清除该用户(学生角色)在会话中的相关登录状态信息。
session.removeAttribute("student");
// 从会话中移除名为"teacher"的属性,同理,该属性是在教师角色用户登录成功后设置的,用于保存教师用户的相关信息,
// 移除操作清除教师角色用户在会话中的登录状态相关数据。
session.removeAttribute("teacher");
// 从会话中移除名为"admin"的属性,这是针对管理员角色用户登录成功后在会话中保存的相关信息,
// 通过移除该属性,消除管理员角色用户的会话登录状态记录。
session.removeAttribute("admin");
// 使当前会话失效,这一步操作会清除整个会话中的所有属性信息,并且后续该会话相关的请求将无法再获取到之前存储的任何数据,
// 相当于彻底结束了当前用户的会话,实现完整的注销效果。
session.invalidate();
// 重定向到"index.jsp"页面,通常这个页面是网站的首页或者是一个未登录状态下展示的通用页面,
// 在用户注销后将其引导到这个页面,让用户回到初始状态或者未登录时可访问的页面。
response.sendRedirect("index.jsp");
}
// 重写doGet方法在这个类中直接调用doPost方法来处理GET请求意味着GET请求和POST请求在本Servlet中的处理逻辑是一样的
// 即当接收到GET请求时同样会执行上述doPost方法中的操作完成用户注销并跳转到相应页面的功能。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}