SpringBoot的拦截器只能拦截流经DispatcherServlet的请求,对于自定义的Servlet无法进行拦截。
SpringMVC中的拦截器有两种:HandlerInterceptor和WebMvcInterceptor。这两个接口都定义了请求之前、请求之中、请求之后三个函数,以HandlerInterceptor为例进行说明:
- public boolean preHandle(HttpServletRequest req, HttpServletResponse httpServletResponse, Object o)
- public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
- public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
HandlerInterceptor的函数返回值都是boolean,一旦返回false,就不再处理这个请求,所以它真正具有拦截功能。而WebMvcInterceptor作用只是进行初始化,它的三个函数都是void类型的。
要想使用HandlerInterceptor需要如下几个步骤:
实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse httpServletResponse, Object o) throws Exception {
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
添加Configureation
过去可以用xml配置,现在更倾向于用java代码配置
@Configuration
public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}