SpringBoot中的拦截器Interceptor(随笔)
1)定义拦截器:定义一个拦截器类实现HandlerInterceptor接口,重写preHangle()方法;
public class OneInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获得拦截的uri并输出
System.out.println("这里经过了拦截器"+request.getRequestURI());
return true;
}
}
2)注册拦截器:定义一个类继承自WebMvcConfigurationSupport,重写addInterceptors()方法,并在该类上使用@Configuration注解,表明该类为配置类。
@Configuration //表明当前类为配置类
public class OneInterceptorConfig extends WebMvcConfigurationSupport {
//注册拦截器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new OneInterceptor())
// .addPathPatterns("/rjxy/**"); //拦截/rjxy相关的uri请求
.excludePathPatterns("/rjxy/**"); //指定不进行拦截的uri,但拦截其他uri请求
}
}