【配置步骤】
1.为类添加注解@Configuration,配置拦截器
2.继承WebMvcConfigurerAdapter类
3.重写addInterceptors方法,添加需要拦截的请求
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//表示拦截所有的请求
registry.addInterceptor(new InterceptorTest()).addPathPatterns("/*/**");
super.addInterceptors(registry);
}
}
public class InterceptorTest implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("拦截成功");
return false;
}
//HandlerInterceptor仍有其它方法,已省略
}
【测试拦截器】
1.配置mapping方法
@RequestMapping("/interceptor")
@ResponseBody
String interceptorTest() {
return "拦截器未开启";
}
2.不开启拦截器,即把InterceptorTest.preHandle改为return true
3.开启拦截器,即把InterceptorTest.preHandle改为return false
原文地址:https://www.cnblogs.com/likailun/p/8734556.html
时间: 2024-10-29 02:39:45