• SpringMVC通过CROS协议配置跨域访问


    CORS协议:CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。只要服务器实现了CORS接口,就可以跨源通信。

    CORS常见的header:

    • Access-Control-Allow-Origin: http://kbiao.me
    • Access-Control-Max-Age: 3628800
    • Access-Control-Allow-methods: GET, PUT, DELETE, POST
    • Access-Control-Allow-Header: content-type
    • Access-Control-Allow-Credentail: true

    "Access-Control-Allow-Origin"表明它允许" http://kbiao.me "发起跨域请求

    "Access-Control-Max-Age"表明在3628800秒内,不需要再发送预检验请求,可以缓存该结果(上面的资料上我们知道CROS协议中,一个AJAX请求被分成了第一步的OPTION预检测请求和正式请求)

    "Access-Control-Allow-Methods"表明它允许GET、PUT、DELETE的外域请求

    "Access-Control-Allow-Headers"表明它允许跨域请求包含content-type头

    "Access-Control-Allow-Credentials"表明它允许cookies

    定义一个过滤器,命名为SimpleCORSFilter:

    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.HttpServletResponse;
    import org.springframework.stereotype.Component;
    
    @Component
    public class SimpleCORSFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
            response.setHeader("Access-Control-Allow-Credentials","true");
            chain.doFilter(req, res);
        }
    
        public void init(FilterConfig filterConfig) {}
    
        public void destroy() {}
    
    }

     配置Web.xml使得过滤器生效

    <filter>
          <filter-name>cors</filter-name>
          <filter-class>packageName.SimpleCORSFilter</filter-class>
    </filter>
    <filter-mapping>
          <filter-name>cors</filter-name>
          <url-pattern>/*</url-pattern>
    </filter-mapping>

     spring 4.2+ 可以通过注解实现:@CrossOrigin(origins = “ ”)

  • 相关阅读:
    python+webdriver(二)
    python+webdriver(一)
    重逢
    在C,C++,java和python运行时解释器和编译器的区别
    hive调优
    github 操作指南
    jupyter 启动时的问题
    海量数据模型实施方法论
    python之Tkinker学习
    使用cmd命令行进行本地证书读取
  • 原文地址:https://www.cnblogs.com/TiffanyHYY/p/7151519.html
Copyright © 2020-2023  润新知