• 跨域问题解决


    当一个请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域,出现跨域问题时,会遇到No 'Access-Control-Allow-Origin' header is present on the requested resource错误

    基于CORSFilter可以解决跨域问题,具体代码如下:

    public class CORSFilter implements Filter {
        private FilterConfig filterConfig;
        @Override
        public void destroy() {
        }
        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
            throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) sresponse;
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");
            response.addHeader("Access-Control-Max-Age", "1800");// 30 min
            chain.doFilter(srequest, sresponse);
        }
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
        }
    }

    添加filter配置

    <filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.zhougl.filter.CORSFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>

    也可以在浏览器的快捷方式中添加--args --disable-web-security --user-data-dir配置解决客户端的跨域问题(不安全,不推荐,临时使用)

    如果是flash的跨域,则需要在被访问端添加crossdomain.xml,代码示例如下:

    <cross-domain-policy>
    <site-control permitted-cross-domain-policies="all"/>
    <allow-access-from domain="*"/>
    <allow-http-request-headers-from domain="*" headers="*"/>
    </cross-domain-policy>

    关于crossdomain.xml的具体文档参考:

    https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html

    crossdomain.xml的存放有两种方式:

    1、存放在域名的根目录下,比如https://www.taobao.com/crossdomain.xml

    2、如果不存在根目录下,而是具体的某个web项目下,则需要在flash的as脚本中加载配置

    Security.loadPolicyFile("http://ip:port/webappname/crossdomain.xml");
  • 相关阅读:
    Netty ChannelHandler组件作用
    Netty Channel组件作用
    Netty NioEventLoop自定义任务处理
    NIO与BIO
    JDK ByteBuffer与Netty ByteBuf
    linux-源码软件管理-yum配置
    typora使用快捷键
    远程连接mysql库问题
    MVC 后台处理 json格式的日期
    使用 SqlClient 创建数据库连接并获取数据
  • 原文地址:https://www.cnblogs.com/yytxdy/p/12341897.html
Copyright © 2020-2023  润新知