tomcat跨域以及session丢失的解决方案

来源:互联网 发布:安卓软件收费 编辑:程序博客网 时间:2024/05/22 01:46

公司由于要搞跨域问题,写写大概思路!


一、后台配置。

       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调用!!!




0 0
原创粉丝点击