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

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

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 map  = (HashMap) 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 map = null;
		int num= 0;
		if(o==null) {
			map = new HashMap();
		}else {
			map  = (HashMap) 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);
	}

 

 

 

 

 

你可能感兴趣的:(JAVA)