springboot 添加 Filter过滤

Posted 代码之间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 添加 Filter过滤相关的知识,希望对你有一定的参考价值。

通过注解方式完成

  1. 编写一个Filter类:
package com.test.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "ResponseFilter")
public class ResponseFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpServletRequest reqs = (HttpServletRequest) servletRequest;

        // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

注解 @WebFilter(urlPatterns = "/*", filterName = "ResponseFilter") 表示/*所有请求都走这个filter,这个filter。

  1. 在springboot的启动类加一个扫描注解: @ServletComponentScan("com.test.filters") // 过滤器,基于注解方式
package com.test;

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

@SpringBootApplication
@ServletComponentScan("com.test.filters") // 过滤器,基于注解方式
public class TourismApplication {
	public static void main(String[] args) {
		SpringApplication.run(TourismApplication.class, args);
	}

}

大功告成

以上是关于springboot 添加 Filter过滤的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot2.x将Filter过滤器添加到容器

SpringBoot自定义Filter

springboot(11)过滤器Filter

SpringBoot--Filter过滤器

springboot2.1中添加过滤器配置

Springboot 使用过滤器进行加密解密