package com.copy.trade.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

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

// 已迁移至 WebMvcConfigration.corsFilter()，使用 Spring CorsFilter（order=0）统一处理跨域
// @Component
// @Order()
// @WebFilter(urlPatterns = "/*",filterName = "crossDomainFilter")
public class CrossDomainFilter implements Filter {

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

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //设置跨域请求
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3628800"); //设置过期时间
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Access-Control-Allow-Origin,Content-Type,Accept,client_id,token,EX-SysAuthToken,EX-JSESSIONID,Accept-Language,Authorization");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(200);
            return;
        }
        chain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}
