欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot的filter(过滤器)简单使用实例详解

程序员文章站 2024-02-28 23:37:46
过滤器(filter)的注册方法和 servlet 一样,有两种方式:代码注册或者注解注册 1.代码注册方式 通过代码方式注入过滤器 @bean pub...

过滤器(filter)的注册方法和 servlet 一样,有两种方式:代码注册或者注解注册

1.代码注册方式

通过代码方式注入过滤器

@bean
  public filterregistrationbean indexfilterregistration() {
    filterregistrationbean registration = new filterregistrationbean(new indexfilter());
    registration.addurlpatterns("/");
    return registration;
  }

indexfilter.java类:

package com.example.filter;
import java.io.ioexception;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
public class indexfilter implements filter{
  @override
  public void destroy() {
    system.out.println("filter destroy method");
  }
  @override
  public void dofilter(servletrequest arg0, servletresponse arg1, filterchain arg2)
      throws ioexception, servletexception {
    system.out.println("filter dofilter method");
  }
  @override
  public void init(filterconfig arg0) throws servletexception {
    system.out.println("filter init method");
  }
}

2.注解方式

通过注解方式注入过滤器

indexfilter2.java类

package com.example.filter;
import java.io.ioexception;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.annotation.webfilter;
@webfilter(urlpatterns = "/*", filtername = "indexfilter2")
public class indexfilter2 implements filter{
  @override
  public void destroy() {
    system.out.println("filter2 destroy method");
  }
  @override
  public void dofilter(servletrequest arg0, servletresponse arg1, filterchain arg2)
      throws ioexception, servletexception {
    system.out.println("filter2 dofilter method");
  }
  @override
  public void init(filterconfig arg0) throws servletexception {
    system.out.println("filter2 init method");
  }
}

把注解加到入口处启动即可

@springbootapplication
@servletcomponentscan
public class springbootsimpleapplication {
  public static void main(string[] args) {
    springapplication.run(springbootsimpleapplication.class, args);
  }
}

以上所述是小编给大家介绍的spring boot的filter(过滤器)简单使用,希望对大家有所帮助