当前位置: 首页 > news >正文

SpringBoot拦截器的使用介绍

SpringBoot拦截器的使用介绍

本篇文章主要讲的是 SpringBoot 拦截器的使用介绍。

1、定义拦截器

拦截器:所谓拦截器,就是能够在进行某个操作之前拦截请求,如果请求符合条件就允许在往下执行。

定义拦截器的几种方式。

1.1 实现HandleInterceptor接口

自定义拦截器类实现HandleInterceptor接口,并使用@Component注解标注为一个组件。

根据三种情况,可以在不同的方法针对请求进行额外的处理。

在preHandle中,可以进行权限校验,安全控制。

在postHandle中,可以对返回来的ModelAndView进行处理,这个时候还未渲染视图。

在afterCompletion中,请求已经完成,页面已经渲染,数据已经返回。这个时候可以做一些资源清理,或者

记录请求调用时间,做性能监控

public class MySelfInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("在业务处理器处理请求之前被调用");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("在业务处理器处理请求执行完成后,生成视图之前执行");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("在DispatcherServlet完全处理完请求后被调用");}
} 

1.2 继承HandleInterceptorAdapter类

自定义拦截器类继承HandleInterceptor接口的实现类HandleInterceptorAdapter来定义,并使用@Component

注解标注为一个组件。建议使用此方式可以根据需要覆盖一些方法

可以看到HandlerInterceptorAdapter类底层是实现了HandlerInterceptor接口,多了两个方法,要比

实现HandlerInterceptor接口的方式功能强大。

这两个方法都是HandlerInterceptorAdapter类实现的

org.springframework.web.servlet.AsyncHandlerInterceptor接口提供的,而AsyncHandlerInterceptor接

口又继承了HandlerInterceptor接口,所以HandlerInterceptorAdapter底层是实现类HandlerInterceptor接

口。

@Component
public class MyInterceptor extends HandlerInterceptorAdapter {public SingleLoginInterceptor() {super();}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return super.preHandle(request, response, handler);}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {super.postHandle(request, response, handler, modelAndView);}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {super.afterCompletion(request, response, handler, ex);}@Overridepublic void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {super.afterConcurrentHandlingStarted(request, response, handler);}
}

1.3 实现WebRequestInterceptor接口

自定义拦截器类实现WebRequestInterceptor接口,并使用@Component注解标注为一个组件。

两个实现接口方式的异同点 相同点 都可以实现controller层的拦截请求 不同点

1、WebRequestInterceptor的入参WebRequest是包装了HttpServletRequest 和HttpServletResponse的,

通过WebRequest获取Request中的信息更简便。

2、WebRequestInterceptor的preHandle是没有返回值的,说明该方法中的逻辑并不影响后续的方法执行,

所以这个接口实现就是为了获取Request中的信息,或者预设一些参数供后续流程使用。

3、HandlerInterceptor的功能更强大也更基础,可以在preHandle方法中就直接拒绝请求进入controller方

法。

4、使用场景:这个在上条已经说了,如果想更方便获取HttpServletRequest的信息就使用

WebRequestInterceptor,当然这些HandlerInterceptor都能做,只不过要多写点代码

@Component
public class MyInterceptor implements WebRequestInterceptor {@Overridepublic void preHandle(WebRequest webRequest) throws Exception {}@Overridepublic void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {}@Overridepublic void afterCompletion(WebRequest webRequest, Exception e) throws Exception {}
}

1.4 实现RequestInterceptor接口

自定义类实现RequestInterceptor接口,此方式为微服务Feign调用的自定义拦截器,实现各个微服务之间的参数

传递。

@Configuration
public class CenterinsRequestInterceptor implements RequestInterceptor {@Overridepublic void apply(RequestTemplate requestTemplate) {}
}

2、小插曲 @Configuration和@Component区别

这里使用了@Configuration注解而不是@Component,其实@Configuration本质上也是一个@Component,只

不过前者描述的类中所有用@Bean标记的方法都会由CGLIB动态代理执行,在首次调用的时候会执行,然后把执

行结果放到Spring上下文,之后对该方法的调用都是从Spring上下文上取的结果,所以都是指同一个实例。而使用

了@Component,所有用@Bean标记的方法都是纯Java调用,每次都是生成不同的实例对象。如果要让使用了

@Compnent注解的类中其@Bean标记的方法生成都是同一个实例,只需要使用@AutoWired标记属性,自动注入

即可。

@Configuration
public class MyBeanConfig {@Beanpublic Country country(){return new Country();}@Beanpublic UserInfo userInfo(){return new UserInfo(country());}}// 以上代码 等同于以下代码 // 以下代码去掉Autowired注入,则country方法是不同的实例对象。@Component
public class MyBeanConfig {@Autowiredprivate Country country;@Beanpublic Country country(){return new Country();}@Beanpublic UserInfo userInfo(){return new UserInfo(country);}}

3、注册拦截器

注册拦截器在springboot中直接使用注解便可实现。

3.1 继承WebMvcConfigurerAdapter类

创建一个自定义类,继承WebMvcConfigurerAdapter类重写addInterceptors方法。

此类在SpringBoot2.0以后已经废除,但仍可使用。推荐使用以下两种方式来代替此方式。

@Configuration
public class WebCofiguration extends WebMvcConfigurerAdapter {public void addInterceptors(InterceptorRegistry registry) {// 将自己定义的拦截器注入进来进行拦截操作registry.addInterceptor(new MySelfInterceptor ()).addPathPatterns("/**").excludePathPatterns("/logout");//过滤器可以添加多个,这里的addPathPatterns的/**是对所有的请求都做拦截。//excludePathPatterns代表排除url的拦截路径,即不拦截}
}

3.2 继承WebMvcConfigurationSupport类

创建一个自定义类继承WebMvcConfigurationSupport类,实现addInterceptors。

此方式会导致默认的静态资源被拦截,这就需要我们手动将静态资源放开。

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {@Overrideprotected void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");super.addInterceptors(registry);}
}

除了重写方法外还需要重写addResourceHandlers方法来释放静态资源

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");super.addResourceHandlers(registry);
}

3.3 实现WebMvcConfigurer接口

创建一个自定义类实现WebMvcConfigurer接口,重写addInterceptors方法。

此方式不会拦截静态资源

@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 实现WebMvcConfigurer不会导致静态资源被拦截registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");}
}

4、应用场景

由于这两种方式的不同:

继承 WebMvcConfigurationSupport类的方式推荐用在前后端分离的项目中,后台不需要访问静态资源(就

不需要放开静态资源了),当然也可以在前后端不分离中,如果需要访问静态资源使用上面的方式重写

addResourceHandlers方法即可;

实现 WebMvcConfigure接口的方式推荐用在非前后端分离的项目中,因为需要读取一些图片、css、js文件

等等,当然也可以使用在前后端分离项目。

5、拦截器执行流程

5.1 单个拦截器

对单个拦截器执行流程解释如下:

程序首先会执行拦截器类中的preHandle()方法,如果该方法返回true,则程序会继续向下执行处理器中的方

法,否则程序将不再往下继续执行。在业务处理器(即控制器Controller类)处理完请求后,会执行

postHandle()方法,然后会通过DispatcherServlet向客户端返回响应,在DispatcherServlet处理完请求后,

才会执行afterCompletion()方法。

因此单个拦截器的执行流程:

prehandle()——Handle(也就是控制器里的方法)——postHandle()——afterCompletion()。

5.2 多个拦截器

在大型的企业级项目中,通常会配置多个拦截器来实现不同的功能。例如我们自定义了三个拦截器A、B、

C。并将它们都注册到同一个拦截器配置类中:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new AInterceptor()).addPathPatterns("/**");registry.addInterceptor(new BInterceptor()).addPathPatterns("/**");registry.addInterceptor(new CInterceptor()).addPathPatterns("/**");}
}

它们的preHandle()方法会按照配置文件中拦截器的配置顺序执行,而它们的postHandle()和

afterCompletion()方法则会按照配置顺序的反序执行。

因此当前我们的三个拦截器执行顺序如下:

preHandleA——preHandleB——preHandleC——Handle——postHandleC——postHandleB——

postHandleA——afterCompletionC——afterCompletionB——afterCompletionA

6、总结

到此这篇关于SpringBoot拦截器的使用介绍的文章就介绍到这了。

http://www.lryc.cn/news/425863.html

相关文章:

  • Spring Boot应用中的资源分离与高效打包实践
  • 分析 avformat_open_input 数据读取过程
  • Apache HOP (Hop Orchestration Platform) VS Data Integration (通常被称为 Kettle)
  • 如何判断一个dll/exe是32位还是64位
  • 加速网页加载,提升用户体验:HTML、JS 和 Vue 项目优化全攻略
  • LVS服务器基础环境配置
  • 【Python OpenCV】使用OpenCV实现两张图片拼接
  • springboot jar -jar centos后台运行的几种方式
  • 【GitLab】使用 Docker 安装 GitLab:配置 SSH 端口
  • 【pdf文件生成】如何将盖章的文件生成PDF文件
  • 铝壳电阻在电路中的作用和影响是什么?
  • # Python 判断入参日期是周几
  • 井字棋游戏(HTML+CSS+JavaScript)
  • HTML 列表和容器元素——WEB开发系列10
  • Java数组的高级使用技巧与性能优化
  • python spyne报No module named ‘http.cookies‘的解决
  • vmware虚拟机玩GPU显卡直通
  • Linux下Oracle 11g升级19c实录
  • haproxy实验-2
  • 動態PPTP代理IP是什麼?
  • 《全面解析 Nginx:从下载安装到高级应用与问题解决》
  • python获取视频时长
  • php-xlswriter实现数据导出excel单元格合并,内容从指定行开始写
  • 注意力模型QKV矩阵与位置向量计算
  • glm4-9B-chat,使用提示工程激活模型最大潜力
  • [Linux]在Ubuntu中如何正确安装python
  • [Vue3 + TS + Vite]文件选择器-组件
  • Chrome书签搜索插件
  • MATLAB算法实战应用案例精讲-【人工智能】联邦学习(二)(附python代码实现)
  • 在 C++ 中实现一个简单的图形用户界面(GUI)应用