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

相关推荐
Q_Q196328847513 分钟前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
摇滚侠23 分钟前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 属性优先级 行内写法 变量选择 笔记42
java·spring boot·笔记
摇滚侠27 分钟前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 总结 热部署 常用配置 笔记44
java·spring boot·笔记
十年小站27 分钟前
一、新建一个SpringBoot3项目
java·spring boot
程序员阿达1 小时前
开题报告之基于SpringBoot框架的路面故障信息上报系统设计与实现
java·spring boot·后端
哞哞不熬夜1 小时前
JavaEE--SpringIoC
java·开发语言·spring boot·spring·java-ee·maven
疯癫的老码农2 小时前
【Linux环境下安装】SpringBoot应用环境安装(五)-milvus安装
linux·spring boot·milvus
Kay_Liang3 小时前
大语言模型如何精准调用函数—— Function Calling 系统笔记
java·大数据·spring boot·笔记·ai·langchain·tools
摇滚侠4 小时前
Spring Boot 3零基础教程,WEB 开发 内容协商机制 笔记34
java·spring boot·笔记·缓存
Json____4 小时前
学习springBoot框架-开发一个酒店管理系统,来熟悉springboot框架语法~
spring boot·后端·学习