1. 思路
访问:前端login.jsp---->后台:如果上次用户选择勾选记住密码,自动填充账号和密码;否则,不填。
如何判断上次是否记住密码?`
第一次登录成功,去判断是否需要记住密码:如果需要记住密码,则往浏览器写cookie;否则,删除cookie。而且cookie的值必须是该用户的账号和密码(例如: loginAct和loginPwd),在下次登录时,判断该用户有没有cookie:如果有,则自动填写账号和密码;否则,不写。且填写的是cookie的值.
最后是 ----->浏览器显示
代码实现:
Controller层:
if(user==null){
//登录失败,用户名或密码错误
returnObject.setCode("0");
returnObject.setMessage("用户名或密码错误!");
}else {
//进一步判断账号是否合法
String nowStr = DateUtils.FormatDateTime(new Date());
if (nowStr.compareTo(user.getExpireTime())>0){
//登录失败,账号过期
returnObject.setCode(Contant.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage("登录失败,账号过期");
}else if("0".equals(user.getLockState())){
//登录失败,状态被锁定
returnObject.setCode(Contant.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage("登录失败,状态被锁定");
}else if (!user.getAllowIps().contains(request.getRemoteAddr())){
//登录失败,IP受限
returnObject.setCode(Contant.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage("登录失败,IP受限");
}else {
//登陆成功
returnObject.setCode(Contant.RETURN_OBJECT_CODE_SUCCESS);
//把user保存到session中
session.setAttribute(Contant.SESSION_USER, user);
//如果需要记住密码,则需要往外写cookie、
if ("true".equals(isRemPwd)) {
Cookie c1 = new Cookie("loginAct", user.getLoginAct());
c1.setMaxAge(10*24*60*60);
response.addCookie(c1);
Cookie c2 = new Cookie("loginPwd", user.getLoginPwd());
c2.setMaxAge(10*24*60*60);
response.addCookie(c2);
}else {
Cookie c1 = new Cookie("loginAct", "1");
c1.setMaxAge(0);
response.addCookie(c1);
Cookie c2 = new Cookie("loginPwd", "1");
c2.setMaxAge(0);
response.addCookie(c2);
}
}
}
login.jsp页面:
1.使用EL表达式获取cookie:
在input标签中使用:value=" ${cookie.loginAct.value}"
value=" ${cookie.loginPwd.value}"
进行自动填写账号和密码
2.在登录页面引入JSTL标签库:
1)<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2)使用if标签进行判断,如果带有cookie值,就自动勾选,为空则不选
代码实现:
<div style="position: absolute; top: 0px; right: 60px;">
<div class="page-header">
<h1>登录</h1>
</div>
<form action="/workbench/index.html" class="form-horizontal" role="form">
<div class="form-group form-group-lg">
<div style="width: 350px;">
<input class="form-control" id="loginAct" type="text" value="${cookie.loginAct.value}" placeholder="用户名">
</div>
<div style="width: 350px; position: relative;top: 20px;">
<input class="form-control" id="loginPwd" type="password" value="${cookie.loginPwd.value}" placeholder="密码">
</div>
<div class="checkbox" style="position: relative;top: 30px; left: 10px;">
<label>
<c:if test="${not empty cookie.loginAct and not empty cookie.loginPwd}">
<input type="checkbox" id="isRemPwd" checked>
</c:if>
<c:if test="${empty cookie.loginAct or empty cookie.loginPwd}">
<input type="checkbox" id="isRemPwd">
</c:if>
十天内免登录
</label>
<span id="msg"></span>
</div>
<button type="button" id="loginBtn" class="btn btn-primary btn-lg btn-block" style="width: 350px; position: relative;top: 45px;">登录</button>
</div>
</form>
</div>