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

相关推荐
m0_7482386317 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
張葒兵3 小时前
记一次命令行启动springboot项目的问题 java -jar的问题
java·spring boot·jar
mah66610 小时前
SpringBoot项目连接Oracle视图报错整理
spring boot·后端·oracle
IT学长编程11 小时前
计算机毕业设计 基于SpringBoot的智慧社区管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·后端·毕业设计·课程设计·论文笔记·1024程序员节
奋斗的小方11 小时前
Springboot基础篇(3):Bean管理
java·spring boot·后端
扣丁梦想家13 小时前
《Spring Boot + MySQL高性能应用实战:性能优化技巧与最佳实践》
spring boot·后端·mysql
Code额13 小时前
Springboot 自动化装配的原理
java·spring boot
夏天的味道٥13 小时前
36. Spring Boot 2.1.3.RELEASE 中实现监控信息可视化并添加邮件报警功能
java·spring boot·后端
计算机学长felix15 小时前
基于SpringBoot的“洪涝灾害应急信息管理系统”的设计与实现(源码+数据库+文档+PPT)
spring boot·毕业设计