登陆功能优化—登陆注销模块
我们登陆后复制后端页面的地址,在退出后直接访问这个地址,这时候发现还是可以进入的
这个就还是之前的那个问题,我们要对注销的账户进行拦截
实现注销功能
思路:移除Session 返回登陆页面
我们前端的页面点击了退出之后会跳转到/jsp/logout.do
我们建立一个Servlet来处理退出请求,并将其xml配置为logout.do
1、创建LoginoutServlet
LoginoutServlet实现的功能很简单,首先先得到Session,然后移除Session中的userCode属性
移除后用户的Session就不再存在了,再重定向到用户的登录页面。但是这时候我们如果直接访问后端页面的地址还是可以进去 ,后面我们要做拦截才行。
package com.lding.servlet.user;
import com.lding.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.AbstractDocument;
import java.io.IOException;
/**
* @program: SMBMS
* @description:
* @author: 王丁
* @date: 2021-11-06 16:06
**/
public class LoginoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的Constants.USER_SESSION
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2、配置web.xml 中的LoginoutServlet
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.lding.servlet.user.LoginoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
拦截优化
当我们访问项目下面所有的jsp页面时,都应进行一次拦截,把无用户Session的拦截掉
这个很显然要在过滤器中实现
我们在filter包下创建一个SysFilter
实现的功能为,首先进行类型转换,因为ServletRequest无法获取session,我们将其转换成HttpServletRequest 。从request中拿到Session,并读取Session中的userCode属性,判断这个user是否为空,如果为空则把他拦截,利用HttpServletResponse的重定向,跳转到error.jsp页面,如果有user,则利用filterChain链继续走
SysFilter
package com.lding.filter;
import com.lding.pojo.User;
import com.lding.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @program: SMBMS
* @description:
* @author: 王丁
* @date: 2021-11-06 16:19
**/
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//过滤器 从Session中获取用户
User user=(User)request.getSession().getAttribute(Constants.USER_SESSION);
if(user==null){
response.sendRedirect(request.getContextPath()+"/error.jsp");
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
public void destroy() {
}
}
在web.xml中配置过滤器
<!-- 用户登陆过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.lding.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>