import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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


@Component
@SuppressWarnings("unused")
public class SimpleCorsFilter implements Filter{
    private Logger logger= LoggerFactory.getLogger(SimpleCorsFilter.class);

    @Value("${com.cors}")
    private String cors;

    @Value("${com.corsheader}")
    private String corsHeader;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        //logger.debug("CORS控制");
        response.setHeader("Access-Control-Allow-Origin", cors);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", corsHeader);
        response.setHeader("Vary", "Origin");
        if(((HttpServletRequest)req).getMethod().toUpperCase().equals("OPTIONS")){
            return;
        }
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}

com.cors=* //设值允许访问的域名 * 表示所有
com.corsheader=authtication,content-type //设值允许传输的header

Access-Control-Allow-Origin //允许哪些域名跨域
Access-Control-Allow-Credentials //是否允许cookies传输
Access-Control-Allow-Headers //允许header中哪些参数传输
response.setHeader("Vary", "Origin"); //告诉CDN等,响应是基于请求者Origin头值进行协商的。
版权声明:本文为keepMoveForevery原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/keepMoveForevery/p/9549885.html