登录过滤器
@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 request=(HttpServletRequest)servletRequest;
HttpServletResponse response=(HttpServletResponse)servletResponse;
String requestURI = request.getRequestURI();
log.info("拦截到请求:{}",requestURI);
String[] urls=new String[]{
"/登录controller/login",
"/登录controller/logout",
"/静态资源/**",
"/静态资源/**",
};
boolean check = check(urls, requestURI);
if(check){
log.info("本次请求不用处理:{}",requestURI);
filterChain.doFilter(request, response);
return;
}
if(request.getSession().getAttribute("登录后保存session")!=null){
log.info("用户已登录,用户ID为:{}",request.getSession().getAttribute("登录后保存的session"));
filterChain.doFilter(request, response);
return;
}
log.info("用户未登录!");
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
public static boolean check(String[] urls, String requestURI){
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if(match){
return true;
}
}
return false;
}
}