跨域过滤器配置

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 跨域配置<br>
 * 跨域资源共享 CORS 详解:http://www.ruanyifeng.com/blog/2016/04/cors.html<br/>
 * HTTP 中文开发手册:https://www.php.cn/manual/view/35587.html
 */
public class CrossFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chiain)
        throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 允许跨域的地址*表示所有
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8848");
        // 表示是否允许发送Cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许跨域的方法
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        // 预检请求的有效期,OPTIONS请求就是想服务端进行探测支持的方法
        response.setHeader("Access-Control-Max-Age", "3600");
        // 跨域时允许的请求头字段
        response.setHeader("Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept,Token,tokenzsk,tokenzsk1");
        // 检测时直接返回
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
        chiain.doFilter(servletRequest, servletResponse);
    }
}

// 注册过滤器
@Bean
public FilterRegistrationBean<CrossFilter> corssFilterRegiste() {
    FilterRegistrationBean<CrossFilter> reFilter = new FilterRegistrationBean<>();
    // 创建并注册TestFilter
    reFilter.setFilter(new CrossFilter());
    // 拦截的路径(对所有请求拦截)
    reFilter.addUrlPatterns("/services/*");
    // 拦截器的名称
    reFilter.setName("CrossFilter");
    // 拦截器的执行顺序。数字越小越先执行
    reFilter.setOrder(1);
    return reFilter;
}

 

posted @ 2020-12-27 12:29  zincredible  阅读(297)  评论(0编辑  收藏  举报