定义
拦截器(Interceptor
) 拦截、中断的意思,类似于 JavaWeb中的Filter,但不如Filter拦截的范围大。
作用
通过将控制器中的通用代码放在拦截器中执行,减少控制器中的代码冗余。
拦截器的特点
- 请求到达会经过拦截器,响应回来同样会经过拦截器
- 拦截器只能拦截控制器相关请求,不能拦截jsp、静态资源相关请求
- 拦截器可以中断请求轨迹
开发拦截器
- 自定义类,并实现接口
HanHandlerInterceptor
中的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| package com.buubiu.interceptors;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("===========1=========="); System.out.println("请求的方法:" + ((HandlerMethod) handler).getMethod().getName()); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("===========3=========="); System.out.println(modelAndView);
}
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("===========4=========="); if (ex != null) { System.out.println(ex.getMessage()); } } }
|
配置拦截器,开发自定义配置类 并实现 WebMvcConfigurer
接口
注意:在springboot2.x版本中自定义拦截器之后出现项目中静态资源 404情况,需要在自定义拦截器的配置中添加如下两种之一的配置
- 在方法
addInterceptors
中添加排除资源配置
- 在方法
addResourceHandlers
中添加不经过拦截器的资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package com.buubiu.config;
import com.buubiu.interceptors.MyInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration public class InterceptorConfig implements WebMvcConfigurer {
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/hello/**") .excludePathPatterns("/hello/word","classpath:/templates/") .excludePathPatterns("classpath:/static/","classpath:/templates/"); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/","classpath:/templates/"); } }
|