第一步:定义拦截器类,实现HandlerInterceptor接口。(或者继承HandlerInterceptorAdaptor类)
Tips:这里在preHandle里面 默认是return false(拦截,请求终止),true(放行继续执行后面的流程)。
public class SysInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor preHandle##############");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor postHandle##############");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor afterCompletion##############");
}
}
第二步:
1.定义一个WebMvcConfig类并继承WebMvcConfigurerAdapter。
2.用@Configuration注解类 :相当于定义一个配置文件类,里面定义了许多@Bean 标注的方法,让Spring容器统一管理。
3.重写addInterceptors(InterceptorRegistry registry)方法,并注册我们自己的拦截器。
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public SysInterceptor getSysInterceptor(){
return new SysInterceptor();
}
/**
* 拦截器执行顺序和注册顺序一致
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//排除不需要拦截的请求地址
String[] excludeUri ={"/test/static/*.html","/test/img/*.*"};
registry.addInterceptor(getSysInterceptor()).excludePathPatterns(excludeUri);
}
}
到此 Springboot拦截器定义完成。