完善登录功能
- 1、创建自定义过滤器LoginCheckFiler
- 1.1通过@WebFilter创建过滤器
- 1.2 验证是否可以拦截请求
- 1.3 代码
- 2、在启动类加入注解@ServletComponentScan 用来扫描过滤器
- 触发所有的过滤器@ServletComponentScan
- 3、完善过滤器的处理逻辑
- 3.1判断是否需要是要放行的请求
- 3.2判断用户是否登录
- 3.3如果没有登录返回请求体并携带msg信息
1、创建自定义过滤器LoginCheckFiler
1.1通过@WebFilter创建过滤器
1.2 验证是否可以拦截请求
1.3 代码
package com.example.ruiji_demo;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;@Slf4j
@SpringBootApplication
@ServletComponentScan
public class RuijiDemoApplication {public static void main(String[] args) {SpringApplication.run(RuijiDemoApplication.class, args);log.info("项目启动成功");}}
2、在启动类加入注解@ServletComponentScan 用来扫描过滤器
触发所有的过滤器@ServletComponentScan
3、完善过滤器的处理逻辑
3.1判断是否需要是要放行的请求
3.2判断用户是否登录
3.3如果没有登录返回请求体并携带msg信息
package com.example.ruiji_demo.filter;import com.alibaba.fastjson2.JSON;
import com.example.ruiji_demo.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;import java.io.IOException;
import java.util.logging.LogRecord;
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;String requestUrl = request.getRequestURI();
String[] urls = new String[]{"/employee/login","/employee/logout","/backeed/**","/front/**"};
boolean check = check(urls,requestUrl);if(check){filterChain.doFilter(request,response);return;}
if(request.getSession().getAttribute("employee") != null){filterChain.doFilter(request,response);return;}response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));return;}public boolean check(String[] urls,String requestUrl){for(String url:urls){boolean match = PATH_MATCHER.match(url,requestUrl);log.info("match:{}",match);if(match){return true;}}return false;}
}