可以防止未登陆的用户去一些特殊页面。实现只有登陆才能去某个页面的功能。

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 1. 获取本次URI
        String requestURI = req.getRequestURI();
        // 2. 定义不需要处理的路径,遇到这些路径直接放行
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
        };
        boolean matchResult = check(urls, requestURI);
        if(matchResult) {
            filterChain.doFilter(req, resp);
            log.info("拦截到的请求:" + requestURI + "放行");
            return ;
        }
        Object employ = req.getSession().getAttribute("employee");
        System.out.println(employ);
        // 3. 需要处理的路径,看看登陆没
        if(employ != null) {
            filterChain.doFilter(req, resp);
            log.info("拦截到的请求:" + requestURI + "放行");
            return;
        }

        // 4. 如果没有登陆,返回R对象,前端会重定向
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截到的请求:" + requestURI + "不放行");
    }
    public boolean check(String urls[], String URI) {
        for(String url: urls) {
            if(PATH_MATCHER.match(url, URI)) return true;
        }
        return false;
    }
}