@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();
//定义不需要请求的路径
String[] urls = new String[]{
"/user/logout",
"/admin/**",
"/user/login"
};
boolean check = check(urls,requestURI);
if(check){
filterChain.doFilter(request,response);
return;
}
//判断登录状态,如果已登录,则直接放行
if(request.getSession().getAttribute("user") != null){
filterChain.doFilter(request,response);
return;
}
//到这里就是没有登录,后面写没有登录后的操作 response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
public boolean check(String[] urls, String requestURI){
for (String url : urls) {
boolean match = PATH_MATCHER.match(url,requestURI);
if(match){
return true;
}
}
return false;
}
}
评论