token存入前端的请求头中,后端获取【秒杀项目】
- 前言
- token存入前端的请求头中,后端获取【秒杀项目】
- token存入前端的请求头中
- 后端获取
前言
2023-08-28 17:34:39
token存入前端的请求头中,后端获取【秒杀项目】
token存入前端的请求头中
function set_login_status() {var $A = $(".user-name");if (!$A) return false;$.ajax({type: "GET",url: SERVER_PATH + "/user/status",xhrFields: {withCredentials: true},beforeSend: function(xhr) {xhr.setRequestHeader('Authorization', 'Bearer ' + window.sessionStorage.getItem("token"));},success: function (result) {if (result.status == "0" && result.data) {$A.text(result.data.nickname);$("#user-info").show();} else {$("#user-info").hide();}}});
}function logout() {$.ajax({type: "GET",url: SERVER_PATH + "/user/status",xhrFields: {withCredentials: true},beforeSend: function(xhr) {xhr.setRequestHeader('Authorization', 'Bearer ' + window.sessionStorage.getItem("token"));},success: function (result) {if (result.status) {alertBox(result.data.message);return false;}alertBox("已经注销!", function(){window.location.href = "./login.html"});}});
}
后端获取
@RequestMapping(path = "/logout", method = RequestMethod.GET)@ResponseBodypublic ResponseModel logout(HttpServletRequest request) {
// session.invalidate();String token = request.getHeader("Authorization");if (StringUtils.isNotEmpty(token)) {redisTemplate.delete(token);}return new ResponseModel();}@RequestMapping(path = "/status", method = RequestMethod.GET)@ResponseBodypublic ResponseModel getUser(HttpServletRequest request) {
// User user = (User) session.getAttribute("loginUser");String token = request.getHeader("Authorization");User user = null;if (StringUtils.isNotEmpty(token)) {user = (User) redisTemplate.opsForValue().get(token);}return new ResponseModel(user);}