当前位置: 移动技术网 > IT编程>开发语言>Jquery > 解决ajax跨域访问sessionid不一致问题

解决ajax跨域访问sessionid不一致问题

2018年12月25日  | 移动技术网IT编程  | 我要评论

根据浏览器的保护规则,跨域的时候我们创建的sessionid是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的sessionid就不会被保存下来,也就是说,每一次的请求,服务器就会以为是一个新的人,而不是同一个人,为了解决这样的办法,下面这种方法可以解决这种跨域的办法。

 
我们自己构建一个拦截器,对需要跨域访问的request头部重写
向下面这样:

 过滤器的配置: 

public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception {
        httpservletresponse res = (httpservletresponse) servletresponse;
        httpservletrequest request=(httpservletrequest)servletrequest;
        res.setcontenttype("textml;charset=utf-8");
        res.setheader("access-control-allow-origin", request.getheader("origin"));
        res.setheader("access-control-allow-methods", "post, get, options, delete");
        res.setheader("access-control-max-age", "0");
        res.setheader("access-control-allow-headers", "origin, no-cache, x-requested-with, if-modified-since, pragma, last-modified, cache-control, expires, content-type, x-e4m-with,userid,token");
        res.setheader("access-control-allow-credentials", "true");
        res.setheader("xdomainrequestallowed","1");
        filterchain.dofilter(servletrequest,servletresponse);
    }

springmvc xml文件配置方法(如果是springmvc):

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描相应的控制器组件,不包含service以及dao -->
    <context:component-scan base-package="org.nf.catering.controller"/>

    <!-- 启用mvc注解驱动-->
    <mvc:annotation-driven/>

    <!-- 全局的跨域访问配置 -->
    <mvc:cors>
        <!-- /** 表示所有请求都将支持跨域方法 -->
        <mvc:mapping path="/**" allow-credentials="true" allowed-origins="*" allowed-methods="get,post,put,delete"/>
    </mvc:cors>

    <!-- 静态资源处理-->
    <mvc:default-servlet-handler/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
        <property name="prefix" value="/web-inf/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
view code

 

在html网页ajax请求:

在ajax 请求是也要加相应的东西
$.ajax({
url:url,
//加上这句话
xhrfields: {
           withcredentials: true
       },
       crossdomain: true,
 
success:function(result){
alert("test");
},
error:function(){
}
});
 
 
这样我们再跨域测试的时候,就会发现我们的sessionid是一样的了,这样就实现了跨域并且保证在同一个session下。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网