tomcat跨域以及session丟失的解決方案

公司由於要搞跨域問題,寫寫大概思路!


一、後臺配置。

       1.在後臺項目中導入:cors-filter-2.5.jar和java-property-utils-1.10.jar。如果是maven項目可以直接去maven倉庫下載。

       2.項目下的web.xml配置。

        <filter>
	    <filter-name>CORS</filter-name>
	    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
	    <init-param>
	     <param-name>cors.allowOrigin</param-name>
	        <param-value>*</param-value>
	    </init-param>
	    <init-param>
	     <param-name>cors.supportedMethods</param-name>
	        <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
	    </init-param>
	    <init-param>
	     <param-name>cors.supportedHeaders</param-name>
	        <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified,app_key</param-value>
	    </init-param>
	    <init-param>
	        <param-name>cors.exposedHeaders</param-name>
	        <param-value>Set-Cookie</param-value>
	    </init-param>
	    <init-param>
	        <param-name>cors.supportsCredentials</param-name>
	        <param-value>true</param-value>
	    </init-param>
	</filter>
	<filter-mapping>
	    <filter-name>CORS</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
後臺就這兩步即可,然後在另一臺服務器即可訪問接口。


但是別高興的太早。如果後臺沒有登錄、沒有session這樣就大功告成,但現實是殘酷的。

下面以angularjs爲例,去調用跨域之後的接口。


二、angularjs請求接口。

解決方法十分簡單。
在我們每一次的數據請求中,瀏覽器都會向後臺發送一個JSession,後臺會根據這個值自動查找Id爲JSession的那個session對象。但是當跨域時,JSession的值每次都會改變,後臺就會以爲是新的一個會話打開,於是又去創建了一個新的Session對象,而原來的Session對象就找不到了。


解決這個問題的方法很簡單,就是在請求中將withCredentials設爲true,然後每次請求的頭中就會帶有cookie的值,cookie中就記錄了JSession值,因此Session就不會丟失了。

在AngularJS中,可以通過全局設置,使得withCredentials爲true

var utils = angular.module('Utils', []);  
    utils.config(['$httpProvider', config]);  
    function config($httpProvider) {  
            $httpProvider.defaults.withCredentials = true;  
    }  

然後讓在所有的app中都注入'Utils',就會將所有的請求頭中的withCredentials設置爲true,這樣Session就不會丟失啦。
當然也可以通過以下方法來設置當前請求的withCredentials。
$http.xhr.withCredentials  


我想ajax估計也類似,有讀者遇見可以試試ajax調用!!!




發佈了108 篇原創文章 · 獲贊 13 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章