token的保存和获取,本次说的方法只是其中一种,案例简单,后续复杂性可自行优化
function checkForm() {
var oUser = document.getElementById(‘user‘);
var oPswd = document.getElementById(‘pwd‘);
if(remember.checked) {
setCookie(‘user‘, oUser.value, 90); //保存帐号到cookie,有效期7天
setCookie(‘pwd‘, oPswd.value, 90); //保存密码到cookie,有效期7天
}
$.ajax({
url: "/loginauth/login",
type: "post",
dataType: "json",
/*指定ajax和servlet之间数据交互的格式*/
data: {
userName: oUser.value,
password: oPswd.value,
ip:queryIp()
},
async: true,
success: function(result) {
if (result.code==100){
var token=result.token
document.cookie=token;
window.location.href = "/index?token="+token;
}
}
});
//************************
}
@RequestMapping("/loginauth/login") @ResponseBody public Map<String,Object> loginAuth(String userName, String password){ Map<String,Object> result=new HashMap<>(); if ("admin".equals(userName)&&"123".equals(password)){ result.put("code","100"); result.put("token",userName+""+password); result.put("message","登录成功"); return result; } result.put("code","-100"); result.put("message","登录失败"); return result; }
@RequestMapping("/home") @ResponseBody public Map<String,Object> home(@RequestHeader Map<String,String> headers,HttpServletRequest request ){ headers.forEach((key,value)->{ //logger.info(key+","+value); }); String token=request.getHeader("access-token"); logger.info("token:{}",token); Map<String,Object> map=new HashMap<>(); if (StringUtils.isEmpty(token)){ map.put("code","-100"); map.put("message","token获取失败"); } map.put("code","100"); map.put("message","token获取成功,token="+token); return map; }
<div class="container"> <h1><span th:text="${nickname}"></span>,欢迎登陆系统!</h1> <button class="btn btn-success" id="add" >添加</button> <a class="btn btn-default" href="/login" role="button">退出</a> </div> </body> <script> $(function(){ $("#add").click(function(){ var token = document.cookie.split(";")[0]; $.ajax({ type:"get", url:"/home", dataType:"json", headers:{ ‘access-token‘:token }, success:function (data) { alert("data.message="+data.message); } }) }); }); </script>
以上就是本次的全部代码