AngularJS实现cookie跨域

来源:互联网 发布:网络的物理结构 编辑:程序博客网 时间:2024/06/08 00:53
前后端分离被越来越多的公司重视利用,然后带来的最棘手的问题就是,用户信息应如何保存。

一、场景描述

以Java为后台,AngluarJS做前端为例进行描述:当用户在界面登录时,需把用户信息(如uid)存入后台JAVA系统中,用于前后端所处主域可能不同,所有采用常规的session进行保存已不能满足其业务场景。
解决方案:采用cookie进行存储,当cookie被禁止后采用浏览器本地存储localstorage。
采用cookie进行存储时,会出现跨域问题(即AngularJS访问JAVA端,需携带信息存入到JAVA服务端cookie中)。

二、AngularJS实例

AngularJS:
<pre name="code" class="javascript">function getAdustryController($scope,$http){$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'withCredentials':true}).success(function(data){$scope.industries = data;});}
JAVA:
public String execute(){/* 要存入的cookie信息 */Cookie cookie = new Cookie("test_test","321");cookie.setMaxAge(3600);response.addCookie(cookie);/* This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact domain. */response.setHeader("Access-Control-Allow-Origin", "http://test.domain.cn"); //请求源response.setHeader("Access-Control-Allow-Methods","POST"); //请求方式POST, GET, OPTIONSresponse.setHeader("Access-Control-Max-Age", "3600"); //有效期response.setHeader("Access-Control-Allow-Headers", "Content-Type, *"); //请求头类型response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域SiteHandlerAction SiteHandler = (SiteHandlerAction) BeansFactory.getBean(SiteHandlerAction.class);List<IndustryCategory> list = SiteHandler.getAllIndustryCategory(); //所有的分类集合JSONArray jsonArray = JSONArray.fromObject(list); //将list转为jsonString json = jsonArray.toString(); //转为json字符串//将字符串写进输出流try {PrintWriter write = response.getWriter();write.print(json);write.close();} catch (IOException e) {e.printStackTrace();}return NONE;}

三、Jquery实例:

$.ajax("http://localhost/ajax/getAllIndustryCategoty.pt",{type:"POST",data:{languageColumn:'name_eu'},xhrFields:{withCredentials: true},crossDomain::true,success:function(data, status, xhr){}});

四、常用浏览器查看所有cookie信息方式

Google浏览器查看本机所有cookie信息:依次点击设置--高级选项--内容设置--cookies--选择“显示cookies和其他网站数据”按钮就可以看到了
firefox浏览器查看本机所有cookie信息:依次点击设置--选项--隐私--移除单个Cookie

五、header信息:

Access-Control-Allow-Origin: <origin> | * 授权的源控制Access-Control-Max-Age: <delta-seconds>授权的时间Access-Control-Allow-Credentials: true | false控制是否开启与Ajax的Cookie提交方式Access-Control-Allow-Methods: <method>[, <method>]*允许请求的HTTP MethodAccess-Control-Allow-Headers: <field-name>[, <field-name>]*控制哪些header能发送真正的请求    

参考文章:http://my.oschina.net/blogshi/blog/303758
4 0
原创粉丝点击