JAVA密码输入错误3次,锁定账号30分钟简单实现(不操作数据库)

public Object login(User user,HttpSession session) throws Exception {
    	String username = user.getUsername();
    	String password = user.getPassword();
    	if(!checkLock(session, username)) {
    		throw new CustomException(StatusCode.ERROR_CODE,"该账号已被锁定");
    	}
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
        	throw new CustomException(StatusCode.ERROR_CODE, "用户名和密码不能为空!");
        }
        User  u = getByUsername(username);
        if (u == null) {
        	throw new CustomException(StatusCode.ERROR_CODE, "用户名不存在!");
        }
        if(!MD5Util.checkpassword(password, u.getPassword())) {
        	//新增登录失败记录
        	addFailNum(session, username);
        	throw new CustomException(StatusCode.ERROR_CODE, "用户名或密码错误!");
        }
      //清空登录失败记录
        cleanFailNum(session, username);

    ......
}
/**
	 * 校验用户登录失败次数
	 * @param session
	 * @param username
	 * @return
	 */
	public boolean checkLock(HttpSession session,String username) {
		Object o = session.getServletContext().getAttribute(username);
		if(o==null) {
			return true;
		}
		HashMap<String,Object> map  = (HashMap<String, Object>) o;
		int num  = (int) map.get("num");
		Date date = (Date) map.get("lastDate");
		long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
		if(num>=3&&timeDifference<30) {
			return false;
		}
		return true;
	}
	/**
	 * 新增用户登录失败次数
	 * @param session
	 * @param username
	 */
	public void addFailNum(HttpSession session, String username) {
		Object o = session.getServletContext().getAttribute(username);
		HashMap<String,Object> map = null;
		int num= 0;
		if(o==null) {
			map = new HashMap<String,Object>();
		}else {
			map  = (HashMap<String, Object>) o;
			 num  = (int) map.get("num");
			 Date date = (Date) map.get("lastDate");
			 long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
			 if(timeDifference>=30) {
				 num=0;
			 }
		}
		map.put("num", num+1);
		map.put("lastDate", new Date());
		session.getServletContext().setAttribute(username, map);
	}
	/**
	 * 清理用户登录失败的记录
	 * @param session
	 * @param username
	 */
	public void cleanFailNum(HttpSession session, String username) {
		session.getServletContext().removeAttribute(username);
	}

 

 

 

 

 

  • 11
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值