场景:前端搭建本地服务器,访问我的本地服务器接口 进行联调;
服务器代码:
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public CSResponse login(HttpServletRequest request, @RequestBody LoginRequest loginBean) {
String workId = loginBean.getUserNum();
String password = loginBean.getPassword();
if (StringUtils.isBlank(workId) || StringUtils.isBlank(password)) {
//用户名或密码为空
throw new ErrorCodeException(ErrorEnum.CONFIRM_PASSWORD_WRONG);
}
UserEntity user = userService.login(workId, password);
if (null != user) {
HttpSession session = request.getSession();
session.setAttribute(CSContents.USER_SESSION, user);
UserModelVO userModelVO = UserModelConverter.initUserModelIVOValues(user);
CSResponse loginResponse = new CSResponse();
loginResponse.setDetailInfo(userModelVO);
return loginResponse;
} else {
throw new ErrorCodeException(ErrorEnum.USER_NOT_EXITS);
}
}
/** * 用户获取接口 * * @param request * @return */ @RequestMapping(value = "/getUserSession", method = RequestMethod.GET) @ResponseBody public CSResponse getUserSession(HttpServletRequest request) { UserEntity user = (UserEntity) request.getSession().getAttribute(CSContents.USER_SESSION); CSResponse loginResponse = new CSResponse(); if (null != user) { UserModelVO userModelVO = UserModelConverter.initUserModelIVOValues(user); loginResponse.setDetailInfo(userModelVO); return loginResponse; } else { return loginResponse; } }前端调用getUserSession接口刷新后获取不到session里面的值,经过debug发现session的ID发生变更;
为了排除原因,在一台服务器上进行操作,前端将代码长传到仓库对应的路径,结果发现sessionID没有发生变更,由此可见是由于跨域请求出现的问题;
解决方案:前端加上一下代码片段(crossDomain:true 属性):
$.ajax({ type: (!_method ? "post" : _method), contentType: "application/json; charset=utf-8", dataType: "json", url: _url, async: true, crossDomain: true, data: JSON.stringify(_data), success: function (data) { if (data.code == 0) { _callback(data); } else { alert(data.desc); } } });