springboot 添加 Filter过滤
通过注解方式完成
- 编写一个
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。
- 在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);
}
}
大功告成
travel between codes