码迷,mamicode.com
首页 > 其他好文 > 详细

跨域过滤器配置

时间:2020-12-31 12:54:09      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:html   als   ide   oss   set   header   color   public   tor   

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;
}

 

跨域过滤器配置

标签:html   als   ide   oss   set   header   color   public   tor   

原文地址:https://www.cnblogs.com/zincredible/p/14196881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!