现在的位置: 首页 > 编程语言 > 正文

SpringBoot使用过滤器Filter过程解析

2020年02月13日 编程语言 ⁄ 共 2529字 ⁄ 字号 评论关闭

这篇文章主要介绍了Spring Boot使用过滤器Filter过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

首先我们说说什么是过滤器,过滤器是对数据进行过滤,预处理过程,当我们访问网站时,有时候会发布一些敏感信息,发完以后有的会用*替代,还有就是登陆权限控制等,一个资源,没有经过授权,肯定是不能让用户随便访问的,这个时候,也可以用到过滤器。过滤器的功能还有很多,例如实现URL级别的权限控制、压缩响应信息、编码格式等等。

过滤器依赖servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤。下面简单的说说Spring Boot里面如何增加过滤器。

1、引入spring-boot-starter-web

在pom.xml 中引入spring-boot-starter-web包。

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

2、建立过滤器程序

@Order(1):表示过滤器的顺序,假设我们有多个过滤器,你如何确定过滤器的执行顺序?这个注解就是规定过滤器的顺序。

@WebFilter:表示这个class是过滤器。

里面的参数,filterName 为过滤器名字,urlPatterns 为过滤器的范围,initParams 为过滤器初始化参数。

过滤器里面的三个方法

init : filter对象只会创建一次,init方法也只会执行一次。

doFilter : 主要的业务代码编写方法,可以多次重复调用

destroy : 在销毁Filter时自动调用(程序关闭或者主动销毁Filter)。

@Order(1)@WebFilter(filterName = "piceaFilter", urlPatterns = "/*" , initParams = { @WebInitParam(name = "URL", value = "http://localhost:8080")})public class PiceaFilter implements Filter { private String url; /** * 可以初始化Filter在web.xml里面配置的初始化参数 * filter对象只会创建一次,init方法也只会执行一次。 * @param filterConfig * @throws ServletException */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.url = filterConfig.getInitParameter("URL"); System.out.println("我是过滤器的初始化方法!URL=" + this.url + ",生活开始........."); } /** * 主要的业务代码编写方法 * @param servletRequest * @param servletResponse * @param filterChain * @throws IOException * @throws ServletException */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是过滤器的执行方法,客户端向Servlet发送的请求被我拦截到了"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("我是过滤器的执行方法,Servlet向客户端发送的响应被我拦截到了"); } /** * 在销毁Filter时自动调用。 */ @Override public void destroy() { System.out.println("我是过滤器的被销毁时调用的方法!,活不下去了................" ); }}

3、建立Contoller类

这个类比较简单,不做特别说明

@RestControllerpublic class PiceaContoller { @RequestMapping("/query") public void asyncTask() throws Exception { System.out.println("我是控制类里面的方法,我正在思考..............."); }}

4、启动类中增加注解,自动注册Filter

@ServletComponentScan :在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。

@SpringBootApplication@ServletComponentScanpublic class SpringBootFiFilterApplication { public static void main(String[] args) { SpringApplication.run(SpringBootFiFilterApplication.class, args); }}

5、测试结果

好吧,又到了看疗效的时候了。

在浏览中输入:http://localhost:2001/query

这个时候控制台的输入为如下图片。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: Spring Boot使用过滤器Filter过程解析

以上就上有关SpringBoot使用过滤器Filter过程解析的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.