springboot中filter登录过滤器代码LoginCheckFilter

@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;
    }
}
end
  • 作者:UG666(联系作者)
  • 发表时间:2022-12-27 19:50
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 转载声明:如果是转载博主转载的文章,请附上原文链接
  • 评论