温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot中如何使用使用Filter过滤器

发布时间:2021-07-08 17:04:07 来源:亿速云 阅读:202 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关SpringBoot中如何使用使用Filter过滤器,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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);  }}

看完上述内容,你们对SpringBoot中如何使用使用Filter过滤器有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI