手机短信验证码的实现

<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。但原理都是相同的。。。
 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值