解决CORS跨域问题

首先创建一个实现Filter的cors过滤器

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.ApplicationContext;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述 cors过滤类
 *
 * @author duke
 * @since 2020-11-19
 */
@Slf4j
public class CorsFilter implements Filter {

    private static final String DEFAULT_ALLOW_HEADERS =
        "Origin,x-cbg-victoria-rolename,X-Requested-With,Content-Type,Accept,client_id,appid,uuid,Authorization,TraceID"
            + ",haehead,traceid,x-app-id,x-service-type,x-cbg-language,x-sub-app-id,x-multi-consumer-appid,x-group"
            + ",trackid,Pragma,Cache-Control,x-honor-victoria-rolename,x-pix-app-type,x-pix-app-url,x-pix-csrf-token"
            + ",x-pix-main-role-code,x-pix-page-url,x-csrf-token";

    private ApplicationContext context;

    /**
     * init
     *
     * @param filterConfig param
     * @throws ServletException ex
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * doFilter
     *
     * @param servletRequest param
     * @param servletResponse param
     * @param filterChain param
     * @throws IOException ex
     * @throws ServletException ex
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("request method:{},url:{},servletPath:{}", request.getMethod(), request.getRequestURL(),
            request.getServletPath());
        response.setCharacterEncoding("UTF-8");

        // 配置来源 '*'
        String originHeader = StringVerifyUtil.dealSpecialChar(request.getHeader("Origin"));
        log.info("Duke current request origin= {} ", originHeader);
        response.setHeader("Access-Control-Allow-Origin", originHeader);
        // 允许获取证书
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 配置请求方法
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
        // 配置请求头,如果有自定义的请求头,必须配置
        response.setHeader("Access-Control-Allow-Headers", DEFAULT_ALLOW_HEADERS);

        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
        response.setHeader("Access-Control-Max-Age", "3600"); // 设置过期时间

        if ("OPTIONS".equals(request.getMethod())) {
            log.info("OPTIONS request, let it response OK to browser.");
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        log.info("CorsFilter end------------------------------------------------------ ");
    }

    /**
     * destroy
     */
    @Override
    public void destroy() {

    }

    /**
     * setContext
     *
     * @param context param
     */
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
}

然后在框架上注册这个类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 功能描述
 *
 * @author duke
 * @since 2020-11-19
 */
@Configuration
public class FilterRegistry {

    @Autowired
    ApplicationContext context;

    /**
     * corsFilterRegistrationBean
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean corsFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        CorsFilter corsFilter = new CorsFilter();
        corsFilter.setContext(context);
        registrationBean.setFilter(corsFilter);
        registrationBean.addUrlPatterns("/*"); // 所有路径请求
        registrationBean.setName("CorsFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}

 

上一篇:Java的数据类型


下一篇:地方时与世界时的转换问题