1. 程式人生 > >解決ajax跨域訪問sessionid不一致問題

解決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下。