springboot 添加 Filter过滤

2021-01-30 17:16

阅读:637

标签:with   port   eth   frame   work   pattern   web   headers   res   

通过注解方式完成

  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过滤

标签:with   port   eth   frame   work   pattern   web   headers   res   

原文地址:https://www.cnblogs.com/wangleiblog/p/12819885.html


评论


亲,登录后才可以留言!