原始请求:
$.get('http://localhost/getData').success(function(data){
console.log(data);
})
对应的接口:
@RequestMapping(value = "/getData", method = RequestMethod.GET)
public Object update(HttpSession session) {
if(session.getAttribute("user") == null){
return "未登錄";
}
return "測試";
}
通过debug输出发现,ajax请求一直没有session id,所以无论怎么登录,最终访问这个接口,都取不到user。
解决方式:
全局设置ajax的withCredentials为true$.ajaxSetup({
// 設置Ajax請求可以識別cookie session id
xhrFields: {
withCredentials: true
}
})
或者在ajax中添加上参数
$.ajax({
url : 'http://localhost/getData',
xhrFields: {
withCredentials: true
},
})
附angularjs的$http的配置方式:
angular.module('app').config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
})