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也生效了。

相关推荐
工业甲酰苯胺2 小时前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
bjzhang753 小时前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang3 小时前
Spring Boot 入门面试五道题
spring boot
小菜yh3 小时前
关于Redis
java·数据库·spring boot·redis·spring·缓存
爱上语文5 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱5 小时前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
serve the people5 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
罗政10 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
Java小白笔记13 小时前
关于使用Mybatis-Plus 自动填充功能失效问题
spring boot·后端·mybatis
小哇66614 小时前
Spring Boot,在应用程序启动后执行某些 SQL 语句
数据库·spring boot·sql