解决ajax跨域访问sessionid不一致问题
根据浏览器的保护规则,跨域的时候我们创建的sessionId是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的sessionId就不会被保存下来,也就是说,每一次的请求,服务器就会以为是一个新的人,而不是同一个人,为了解决这样的办法,下面这种方法可以解决这种跨域的办法。
过滤器的配置:
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>
在html网页ajax请求:
在ajax 请求是也要加相应的东西
$.ajax({
url:url,
//加上这句话
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(result){
alert("test");
},
error:function(){
}
});这样我们再跨域测试的时候,就会发现我们的sessionId是一样的了,这样就实现了跨域并且保证在同一个session下。
来源:https://www.cnblogs.com/hhmm99/archive/2018/12/24/10171612.html
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!