在SpringBoot中配置拦截器,主要有下面两个步骤:
1、继承接口 HandlerInterceptor,根据需要重写其中的三个类。
2、在配置类中注入该类。
public class MyInterceptor implements HandlerInterceptor {
//controller执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandler......");
return true;
}
//执行完controller执行之后、视图渲染前调用,可以在该方法里获取或者修改model
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandler......");
}
//一般用于清理资源
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion......");
}
}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1、全部拦截
// registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
//2、拦截指定路径
registry.addInterceptor(myInterceptor()).addPathPatterns("/hello");
}
@Bean
MyInterceptor myInterceptor(){
return new MyInterceptor();
}
}
写个controller测试一下
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("hello");
return "hello";
}
@RequestMapping("/world")
public String world(){
System.out.println("world");
return "world";
}
}
测试结果:
preHandler......
hello
postHandler......
afterCompletion......
world
SpringBoot中还有一终拦截器,WebRequestInterceptor
public class MyWebRequestInterceptor implements WebRequestInterceptor {
@Override
public void preHandle(WebRequest webRequest) throws Exception {
}
@Override
public void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {
}
@Override
public void afterCompletion(WebRequest webRequest, Exception e) throws Exception {
}
}
和HandlerInterceptor比较相似,但是可以发现,该拦截器的preHandler返回值为空,说明该方法并不影响后面方法的执行。那么这个拦截器存在的目的是什么呐?
点进WebRequest:
public interface WebRequest extends RequestAttributes {
@Nullable
String getHeader(String var1);
@Nullable
String[] getHeaderValues(String var1);
Iterator<String> getHeaderNames();
@Nullable
String getParameter(String var1);
@Nullable
String[] getParameterValues(String var1);
Iterator<String> getParameterNames();
Map<String, String[]> getParameterMap();
Locale getLocale();
String getContextPath();
@Nullable
String getRemoteUser();
@Nullable
Principal getUserPrincipal();
boolean isUserInRole(String var1);
boolean isSecure();
发现对reques请求中参数做了进一步处理(@Nullable表示可以为空),更加的方便调用。所以两个拦截器的侧重点不同,HandlerInterceptor功能较为强大,可以拦截请求,可以实现WebRequestInterceptor的所有功能,只是要写的逻辑代码要多一点。更而WebRequestInterceptor倾向于简化获取request参数的过程以及预设参数供后面的流程使用。