版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yswKnight/article/details/79867931
获取手机短信验证码-后端、前端(验证码倒计时)
后端
/**
* 发送手机短信验证码
*
* @return str
* @throws Exception
* @author 王永圣
*/
@RequestMapping(value = "/verifyCode")
public @ResponseBody Map<String, Object> verifyCode(@RequestParam(value = "mobile") String mobile,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
boolean smsSuccess = false;
try {
if (mobile == "") {
map.put("message", "手机号码不能为空");
map.put("result", "error");
return map;
}
//短信验证码随机生成工具类:https://blog.csdn.net/yswknight/article/details/79867280
String verifyCodeRandom = RandomCodeUtil.getRandomNumber(6);
//判断发送次数是否超过最大短信发送次数
Object currentTimes = request.getSession().getAttribute("corMobileTimes" + mobile);
if (currentTimes != null) {
int times = NumberUtil.getInt(currentTimes);
if (times > 5) {
map.put("message", "超过最大短信发送次数");
map.put("result", "error");
return map;
}
}
String msg = "【网站名称】您的短信验证码是【" + verifyCodeRandom + "】。您正在进行注册用户验证操作,如非本人操作,请忽略该短信。";
//调用发送短信接口
smsSuccess = SmsUtils.SmsTest(mobile, msg);
System.out.println(msg);
if (smsSuccess) {
map.put("result", "success");
} else {
map.put("result", "error");
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
前端
html代码
<tr>
<td align="right" width="235px">手机验证码:</td>
<td><input id="smsCode" name="smsCode" type="text" /></td>
<td>
<input type="button" id="sendSms" class="btn btn-primary" value="获取短信验证码" onclick="sendValidateCode(this)" /></td>
</tr>
js代码
/**
* 发送短信验证码
*/
function sendValidateCode(obj){
var mobileReg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
var countdown = 60, timerTag;
var mobile=$("#mobile").val().trim();
if(mobile != ""){
var mobileResult = mobileReg.test(mobile);
if(mobileResult){
$.ajax({
url: "verifyCode",
type: "post",
dataType: "json",
async:false,
data: {mobile:mobile},
beforeSend: function (){
$("#sendSms").attr("disabled","disabled");
$(obj).css("background-color","#999");
},
success: function (data) {
if(data.result=="success"){
alert("验证码发送成功,请注意查收!")
setTime(obj,countdown,timerTag);
}else{
countdown = -1;
}
},
complete: function () {
$("#sendSms").removeAttr("disabled");
},
});
}else{
alert("请输入正确的手机号!");
}
}else{
alert("手机号不能为空,请重新输入");
}
}
/**
* 短信验证码计数
*/
function setTime(obj,countdown,timerTag) {
if (countdown <= 0) {
$(obj).removeAttr("disabled").css("background-color","rgb(24, 197, 133)");
$("#sendSms").attr("onclick","sendValidateCode(this)");
// $(obj).html("重新发送");
$("#sendSms").val("点击重新获取验证码").removeAttr("disabled").removeClass(
"disabled");
countdown = 60;
clearTimeout(timerTag);
} else {
$("#sendSms").attr("disabled", true);//点击了"发送"按钮后,点击失效。
$("#sendSms").addClass("disabled");//置灰
// $(obj).html("重新发送(" + countdown + ")");
$("#sendSms").attr("value","" + countdown + "秒后重新获取验证码");
countdown--;
timerTag = setTimeout(function() {
setTime(obj,countdown,timerTag);
}, 1000);
}
}