登陆三次失败锁定不给登陆。
这里主要的实现方式是数据库表+代码。当然这种方式适合练练手,还有一种更简便的就是用缓存实现,代码节省很多。
基本逻辑是登陆失败累计次数。三次抛出限制定语。
限定根据当前时间和数据库锁定时间进行判断是否解锁。
最后数据状态修改为0.
代码
public Yhxx getLogin(String userName, String pwd) throws ServiceException {
Yhxx yh = yhxxMapper.getYhxxByUserName(userName);
if (yh == null) {
throw new ServiceException("P-1", "用户信息不存在!");
}
String yhDlm = yh.getYhDlm();
if (StringUtils.isEmpty(yh)) {
throw new ServiceException("P-1", "用户不存在!");
}
int num = 0;
Yhdlxx yhdlxx = iYhdlxxMapper.findYhdlxxByUid(yh.getXxbm());
if (!yh.getYhDlmm().equals(MD5Util.encode(pwd))) {
//在数据表中建立数据记录,数据需要uid,错误的次数,锁定的时间。
//不存在则记录
if (yhdlxx == null) {
yhdlxx = new Yhdlxx();
yhdlxx.setUid(yh.getXxbm());
yhdlxx.setFailurenum(1);
iYhdlxxMapper.insterYhdlxx(yhdlxx);
} else {
if (yhdlxx.getFailurenum() == errorPasswordTimes) {
throw new ServiceException("P-1", "登陆密码输入错误" + errorPasswordTimes + "次,请稍后在重试!");
}
num = yhdlxx.getFailurenum() + 1;
//存在则,登陆次数累计,到三次锁定,并加上锁定时间
yhdlxx.setFailurenum(num);
if (num == errorPasswordTimes) {
yhdlxx.setLocktime(new Date());
}
iYhdlxxMapper.updateYhdlxxByUid(yhdlxx);
if (num == errorPasswordTimes) {
throw new ServiceException("P-1", "登陆密码输入错误" + errorPasswordTimes + "次,请(" + errorPasswordLockTime + ")分钟后在重试!");
}
}
int i = errorPasswordTimes - yhdlxx.getFailurenum();
throw new ServiceException("P-1", "密码错误!您还有" + i + "次机会!");
}
//根据锁定时间和当前时间得到之间的分钟数。
if (yhdlxx != null && yhdlxx.getFailurenum() - errorPasswordTimes >= 0) {
//LocalDateTime年月日十分秒;LocalDate日期;LocalTime时间
long minutes = Duration.between(new Timestamp(yhdlxx.getLocktime().getTime()).toLocalDateTime(), LocalDateTime.now()).toMinutes();
if (minutes - errorPasswordLockTime < 0) {
throw new ServiceException("P-1", "登陆密码输入错误三次,请(" + (errorPasswordLockTime - minutes) + ")分钟后在重试!");
}
}
//登陆成清除数据
Yhdlxx yhdlxx1 = new Yhdlxx();
String uid = yh.getXxbm();
yhdlxx1.setUid(uid);
yhdlxx1.setFailurenum(num);
yhdlxx1.setLocktime(null);
iYhdlxxMapper.updateYhdlxxByUid(yhdlxx1);
return yh;
}
数据库
仅供参考!