package com.gz.filter;

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

/**
 * @author LiuchangLan
 * @date 2021/1/29 9:49
 */
public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        // 允许跨域的地址为所有
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的请求头
        httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        // 允许请求的方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        // 非简单请求，只要第一次通过OPTIONS检查 在1小时之内不会在调用OPTIONS进行检测
        httpResponse.addHeader("Access-Control-Max-Age", "3600");
        // 带有Cookie的跨域请求，此值必须设置为true。
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(servletRequest, httpResponse);
    }
}
