解決ajax跨域訪問sessionid不一致問題

根據瀏覽器的保護規則,跨域的時候咱們建立的sessionId是不會被瀏覽器保存下來的,這樣,當咱們在進行跨域訪問的時候,咱們的sessionId就不會被保存下來,也就是說,每一次的請求,服務器就會覺得是一個新的人,而不是同一我的,爲了解決這樣的辦法,下面這種方法能夠解決這種跨域的辦法。html

 
咱們本身構建一個攔截器,對須要跨域訪問的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):web

<?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下。
相關文章
相關標籤/搜索