<pre name="code" class="html">
1页面。js文件
//验证码等待时间
var wait=60;
function time(o) {
if (wait == 0) {
o.attr("onclick", "sendMsg(this);");
o.html("重新发送");
wait = 60;
} else {
o.attr("onclick", "return false;");
o.html("重新发送(" + wait + ")");
wait--;
setTimeout(function() {
time(o);
},
1000);
}
2
<input type="tel" id="checkcode" name="checkcode" placeholder="输入短信验证码" class="block input_for_login" style="width: 50%;">
<a href="#" οnclick="sendSMS(this)" class="pcode">获取验证码</a>
3
/*
* 发送短信验证码
*/
public void sendMsg() {
String mobile = getPara("mobile");//获取手机号
boolean success = false;
int sms = CommonUtils.randomFour();//这里随机数字
TemplateSMS templateSMS = new TemplateSMS();
templateSMS.setTo(mobile);
templateSMS.setParam(sms + "");
System.out.println(sms);
Gson gson = new Gson();
String result = HttpUtils.httpPost(MainConfig.SEND_SMS_URL,
gson.toJson(templateSMS));
System.out.println(result);//这里可以查看打印验证码
if (StringUtils.isNullOrEmpty(result)) {
setAttr("msg", "短信发送失败");
} else {
setSessionAttr("sms_" + mobile, sms + "");// 将验证码放入session中
success = true;
}
setAttr("success", success);
renderJson();
}
随机数字代码
<pre name="code" class="java">/**
* 生成随机四位数字
*
* @return int
*/
public static int randomFour() {
int index = (int) (Math.random() * 9000 + 1000);
return index;
}
HttpUtils-httpost代码
/**
* http post请求(字符串形式)
*
* @param url 请求url
* @param param 请求参数
* @param headers 请求头
* @return 响应字符串
*/
public static String httpPost(String url, String param, Header... headers) {
HttpPost httpPost = new HttpPost(url);
if (ArrayUtils.isNotEmpty(headers)) {
httpPost.setHeaders(headers);
}
httpPost.setEntity(new StringEntity(param, "UTF-8"));
return http(httpPost);
}
调用,测试,
getPara("checkcode")//接收输入的验证码
if (!getPara("checkcode").equals(getSessionAttr("sms_" + mobile))) { // 校验短信验证码
setAttr("msg", "短信验证码不正确");
}
用的jfinal。但原理都是相同的。。。