1.5 版本
先写个拦截器,跟xml配置方式一样,然后将拦截器加入spring容器管理 。接着创建 配置文件类 继承 WebMvcConfigurerAdapter 类,重写父类方法addInterceptors
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { //true放行 false拦截 System.out.println("拦截"); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("preHandle()执行过后再执行"); System.out.println("controller执行前再执行"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("controller执行过后再执行"); } }
@Configuration public class WebConfig extends WebMvcConfigurerAdapter{ @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor) .addPathPatterns("/**") .excludePathPatterns("/index","/login"); super.addInterceptors(registry); } }
2.0 版本跟1.5一样 就是配置类需要的是实现WebMvcConfigurer接口不再是继承 WebMvcConfigurerAdapter 类 ,通过spring代码可以发现 WebMvcConfigurerAdapter implements WebMvcConfigurer 这种关系.
@Configuration public class MvcConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(webInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/asserts/**","/receiveToken","/ssoLogout","/ssoDeleteToken"); ; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }