SpringBoot中使用Filter

SpringBoot中使用Filter

web 开发使用 Controller 基本能解决大部分的需求,但是有时候我们也需要使用 Filter,因为相对于拦截和监听

来说,有时候原生的还是比较好用的,现在就来简单的在 SpringBoot 中使用这些特殊类吧。

在SpringBoot中使用Filter也有两种方式:注解注册Filter和代码注册。

1、pom依赖

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-filter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-filter</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

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

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

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、通过注解的方式进行注册

首先,创建一个 Filter,并使用 WebFilter 注解进行修饰,表示该类是一个 Filter,以便于启动类进行扫描的时候

确认,代码如下:

java 复制代码
package com.example.springbootfilter.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author zhangshixing
 * @date 2021年12月03日 12:40
 * 在SpringBoot中通过注解注册的方式简单的使用Filter
 */
@WebFilter(urlPatterns = "/*", filterName = "myfilter")
public class FileterController implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter初始化中");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("开始进行过滤处理");
        //调用该方法后,表示过滤器经过原来的url请求处理方法
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("Filter销毁中");
    }
}

然后创建一个启动类,该启动类中同样额外添加一个注解用于自动扫描指定包下(默认是与启动类同包下)的

WebFilter/WebServlet/WebListener等特殊类,代码如下:

java 复制代码
package org.springframework.demo.section;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

/**
 * 启动类测试
 * @author chengxi
 */
@SpringBootApplication
//该注解会扫描相应的包
@ServletComponentScan
public class Main {

    public static void main(String[] args){

        SpringApplication.run(Main.class, args);
    }
}

然后启动该类

shell 复制代码
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.1)

Filter初始化中

输入网址:localhost:8080/index,不管我们是否写了该url请求的处理方法,我们查看控制台输出将会发现,

Filter已经被初始化并且被使用了。

shell 复制代码
开始进行过滤处理

3、通过代码注册的方式来使用Filter

首先,创建一个Filter类,该类不使用WebFilter进行修饰:

java 复制代码
package com.example.springbootfilter.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author zhangshixing
 * @date 2021年12月03日 13:45
 * 在SpringBoot中简单使用Filter
 */
public class FileterController1 implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter初始化中");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("开始进行过滤处理");
        //调用该方法后,表示过滤器经过原来的url请求处理方法
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("Filter销毁中");
    }
}

然后,编写启动类,这里的启动类就不能直接使用注解ServletComponentScan来自动扫描了,需要我们手动添加

代码来进行注册,需要用到的注册类是:FilterRegistrationBean,代码方式注册Filter代码如下:

java 复制代码
package com.example.springbootfilter;

import com.example.springbootfilter.filter.FileterController1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringBootFilterApplication {

	public static void main(String[] args) {

		SpringApplication.run(SpringBootFilterApplication.class, args);
	}


	/**
	 * 代码方式注册Bean
	 * @return
	 */
	@Bean
	public FilterRegistrationBean setFilter(){
		FilterRegistrationBean filterBean = new FilterRegistrationBean();
		filterBean.setFilter(new FileterController1());
		filterBean.setName("FilterController");
		filterBean.addUrlPatterns("/*");
		return filterBean;
	}

}

然后,我们启动该类,并输入网址:localhost:8080/index,同样打开控制台查看输出日志将会发现,该

Filter也生效了。

相关推荐
paopaokaka_luck11 小时前
宠物门店经营管理系统(销售与库存联动、进货自动记账、 退换与退款关联、员工个人业绩、ECharts 经营分析、滞销识别与客户分层、宠物档案年龄计算)
前端·javascript·spring boot·mysql·echarts·mybatis·1024程序员节
paopaokaka_luck13 小时前
心理咨询管理系统(WebSocket实时沟通、基于用户的协同过滤、 ECharts多维分析、 预约业务流程、预约校验与定时处理)
java·vue.js·spring boot·mysql·spring·echarts·1024程序员节
2301_322414280413 小时前
springboot农产品交易平台的设计与实现08055-计算机毕设 原创(免费领源码+部署教程+开发环境)
java·spring boot·redis·mysql·tomcat·maven·mybatis
xieliyu.19 小时前
【JavaEE进阶】Spring Boot 日志:从 System.out 到 @Slf4j,6 个级别 + 4 类配置一篇讲透
java·spring boot·spring·java-ee·springboot·logback·slf4j
Mr-Wanter1 天前
Spring Boot 接口签名实践
java·spring boot
余槐i1 天前
开虚拟线程后接口反而更慢:JDK 21 synchronized 锁住载体线程的排查
java·spring boot·redis·mysql·性能优化
RuoyiOffice1 天前
Flowable 状态通知设计:单体用本地事件,微服务如何回写业务状态?
spring boot·微服务·vue3·flowable·ruoyi office·redis stream·流程状态通知
ly76891 天前
Spring Security 过滤器链定制:认证、CORS 与 CSRF 的先后顺序
java·spring boot·spring·spring security·csrf·cors·过滤器链
9527!到!2 天前
Springboot @value读取配置参数踩坑&推荐解决方案
java·spring boot·spring
十年Java程序媛2 天前
Java 面试常问 this、super:构造方法调用顺序避坑
java·开发语言·spring boot·面试·个人开发