SpringBoot利用Cookie实现记住密码

时间:2024-03-07 20:02:19

我们经常能看到网页在登陆页面密码框下面会有一个记住密码的选项,其实它的实现原理是比较简单的。基本的原理就是在登陆时将需要保存的内容放到Cookie中,在需要的时候再从Cookie取出来。

前台html代码:

<div class="container">
	<form th:method="POST" th:action="@{/login}" th:object="${user}">
		<div class="table-responsive">
			<table class="table table-condensed">
			   <tr th:if="${errMsg != \'\'}">
			        <td><span class="text-danger" id="errMsg" th:text="${errMsg}"></span></td>
			   </tr>
                  <tr>
                       <td>用户名</td>
                       <td>
                           <input type="text" class="form-control" id="username" name="username">
                       </td>
                  </tr>
                  <tr>
                       <td>密码</td>
                       <td>
                           <input type="password" class="form-control" id="password" name="password">
                       </td>
                  </tr>
                  <tr>
                       <td></td>
                       <td><input type="checkbox" id="remember" name="remember">remember password</td>
                  </tr>
                  <tr>
                       <td><input type="submit" id="submit" value="登陆"/></td>
                  </tr>
			</table>
		</div>
	</form>
</div>

后台Controller代码:

@PostMapping(value="login")
public String loginCheck(@ModelAttribute("user") User user, Model model
		, HttpServletRequest request, HttpServletResponse response) {
	if(user == null) return "nms/login";
	if(!"1".equals(user.getUsername()) || !"2023".equals(user.getPassword())) {
		model.addAttribute("errMsg", "用户名或密码不正确。");
		return "nms/login";
	}
	if(user.isRemember()) {
		Cookie ckUsername = new Cookie("nms_username", user.getUsername());
		ckUsername.setMaxAge(60*60*24*30);
		response.addCookie(ckUsername);
		Cookie ckPassword = new Cookie("nms_password", user.getPassword());
		ckPassword.setMaxAge(60*60*24*30);
		response.addCookie(ckPassword);
		Cookie ckRemember = new Cookie("nms_remember", "1");
		ckRemember.setMaxAge(60*60*24*30);
		response.addCookie(ckRemember);
	}else {
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(Cookie cookie : cookies) {
				if("nms_username".equals(cookie.getName()) || "nms_password".equals(cookie.getName())
						|| "nms_remember".equals(cookie.getName())) {
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		}
	}
	return "redirect:/nms";
}

前台JavaScript代码:

var cookies = document.cookie.split(\';\');
function getCookie(mkey){
	for(var i = 0; i < cookies.length; i++){
		var kv = cookies[i].split(\'=\');
		if(kv[0].trim()==mkey){
			return kv[1].trim();
		}
	}
	return \'\';
}

window.onload = function(){
	var username = getCookie("nms_username");
	var password = getCookie("nms_password");
	var remember = getCookie("nms_remember");
	if(remember == \'1\'){
		$("#username").val(username);
		$("#password").val(password);
		$("#remember").prop("checked", "checked");
	}
}