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类
这个类比较简单,不做特别说明

@RestController
public class PiceaContoller {

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

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

@SpringBootApplication
@ServletComponentScan
public class SpringBootFiFilterApplication {

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

}

5、测试结果
好吧,又到了看疗效的时候了。
在浏览中输入:http://localhost:2001/query
这个时候控制台的输入为如下图片。

 
 
 
 
 
 
 
 
 
 
 
链接:https://www.jianshu.com/p/2dbb585ffb1c
posted @ 2020-01-19 17:13  panchanggui  阅读(1886)  评论(0编辑  收藏  举报