SpringBoot添加拦截器

【配置步骤】
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

posted @ 2018-07-17 15:25  李凯伦  阅读(322)  评论(0)    收藏  举报