jsp+js+java 手机发送随机数 验证码

jsp

联系手机
发送验证码

js 代码

java 方法
//思路 点击发送验证码 在java方法里面生成六位随机验证码 返回验证码 ,//然后在把验证码保存到session里面 用来验证用户填写的验证码是否正确
/**
* 发送手机/邮箱验证码
* @param request
* @return
*/
@ResponseBody
@RequestMapping(“sendValidateCode”)
public int sendPhoneValidateCode(HttpServletRequest request) {
String type = request.getParameter(“type”);
String munber = request.getParameter(“munber”);
if(StringUtils.isEmpty(munber))//判断等于null就字符串空就返回
return 0;
int num = (int)((Math.random()*9+1)*100000);//生成六位数的随机验证码
HashMap<String, String> value = new HashMap<>();
value.put(type, munber);
value.put(“code”, String.valueOf(num));
request.getSession().setAttribute(type+“ValidateCode”, value);//存入session用于对比
return num;
}

/**
 * 校验验证码是否正确
 * @param request
 * @return
 */
@SuppressWarnings("unchecked")
@ResponseBody
@RequestMapping("validateCodeIfRight")
public boolean validateCodeIfRight(HttpServletRequest request) {
	String phone = request.getParameter("phone");//手机
	String email = request.getParameter("email");//邮箱
	String code = request.getParameter("code");//验证码
	if(StringUtils.isBlank(code)){//判断验证码等于null就返回
		return false;
	}
	if(StringUtils.isNotEmpty(phone)) {//判断手机号不等于空
		HashMap<String, String> phoneValidateCode = (HashMap<String, String>) request.getSession()
				.getAttribute("phoneValidateCode");
		if(phone.equals(phoneValidateCode.get("phone"))) {//手机与最后发送验证码的手机相同
			if(code.equals(phoneValidateCode.get("code")))//验证码相同
				return true;
		}
		return false;
	}else if(StringUtils.isNotEmpty(email)) {//邮箱不等于null
		HashMap<String, String> emailValidateCode = (HashMap<String, String>) request.getSession()
				.getAttribute("emailValidateCode");
		if(email.equals(emailValidateCode.get("email"))) {//手机与最后发送验证码的手机相同
			if(code.equals(emailValidateCode.get("code")))//验证码相同
				return true;
		}
		return false;
	}
	return false;
}

猜你喜欢

转载自blog.csdn.net/qq_42556903/article/details/88431561