请求拦截器优点:
1、拦截非法请求重定向
2、验证用户token
下面是demo程序,有问题的可以在评论区留言
@WebFilter(filterName = "authenticationFilter", urlPatterns = {"/user/*","/detail/*"})
public class AuthenticationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpSession session = servletRequest.getSession();
Object object = session.getAttribute(Constant.USER_SESSION_NAME);
if (Objects.isNull(object)) {
HttpServletResponse servletResponse = (HttpServletResponse) response;
servletResponse.sendRedirect("/login");
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
代码逻辑比较简单易懂。根据springboot的自动配置特性,这样写,就可以达到用户在请求 /user 和 /detail 开头的请求的时候进行过滤了。