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

根据浏览器的保护规则,跨域的时候我们创建的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下。

猜你喜欢

转载自www.cnblogs.com/hhmm99/p/10171612.html