开发中我们可以使用Spring的HandlerInterceptor(拦截器)来实现过滤web请求
拦截器可以在request被响应之前、request被响应之后、视图渲染之前以及request全部结束之后进行某些操作
spring boot配置拦截器的主要步骤为:
1、创建一个继承WebMvcConfigurerAdapter的配置类,并重写 addInterceptors 方法。
2、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。
3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println(">>>MyInterceptor>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if (user != null)
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
else {
System.out.println("未登录");
request.setAttribute("msg","您未登录,请先登录!");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println(">>>MyInterceptor>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println(">>>MyInterceptor>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
@Configuration
public class MyWebAppConfigurer
extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")///**代表拦截所有请求
.excludePathPatterns( "/logincon", "/","/index.html");
super.addInterceptors(registry);
}
}