cors解决ajax跨域问题

来源:互联网 发布:手机说唱软件 编辑:程序博客网 时间:2024/05/21 06:43

    最近项目中做单点登录,使用到了cors解决跨域问题,使用中碰到了一些问题,进行一些简单总结,方便以后使用。cors使用起来其实非常容易,只需要导入cors-filter.jar和java-property-utils.jar即可,这儿我使用的cors-filter-1.7.1.jar和java-property-utils-1.9.1.jar,可以直接去下载

   使用时只需要在web.xml中添加如下配置就可以

   <filter>  
        <filter-name>CORS</filter-name>  
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>  
        <init-param>  
            <param-name>cors.allowOrigin</param-name>
            <param-value>http://abc.cn</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.supportedMethods</param-name>
            <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.exposedHeaders</param-name>
            <param-value>Set-Cookie</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CORS</filter-name>  
        <url-pattern>/*</url-pattern>  
   </filter-mapping>


需要特别说明的是如果cors.supportsCredentials字段设为true,则cors.allowOrigin字段不能使用"*"匹配所有的域名,需要指定具体的域名进行设置。如果cors.supportsCredentials设置为false,则请求将不会把cookie、session等信息带入

遇到问题:

使用cors过程中遇到了两个问题,一个是cors 头Access-Control-Allow-Origin 不匹配,后来排查发现是除了在web.xml中有配置cors.allowOrigin参数之外,又在response中添加了该消息头,导致重复出现问题

另一个问题是cors.supportsCredentials设置为true之后,在ie浏览器下有一个cookie仍然获取不到,但其他浏览器下确是正常的,后来观察了一下该cookie,发现该cookie有设置有效期,将该cookie有效期设置为-1,则能正常获取,不知道ie下获取cookie的机制,有兴趣的可以说下

目前cors也只是有初步了解,能进行基本使用,以后有时间可以再去了解下

0 0
原创粉丝点击