java發送短信驗證碼帶倒計時

分享一個完整的java發送短信驗證碼的完整實例,這是一個官方的使用demo,帶有60秒倒計時功能。javascript

效果:css

 

 

我使用的是榛子云短信平臺, 官網地址:http://smsow.zhenzikj.comhtml

我是java開發者,後端使用了springMvc,前端用的是jsp + jquery前端

下載demo: http://smsow.zhenzikj.com/doc/sdk.html   或者 http://smsow.zhenzikj.com/demo/download.html?fileName=zhenzisms_java_demojava

 

短信驗證碼實現流程
一、構造手機驗證碼,生成一個6位的隨機數字串;
二、使用接口向短信平臺發送手機號和驗證碼,而後短信平臺再把驗證碼發送到制定手機號上
三、將手機號驗證碼、操做時間存入Session中,做爲後面驗證使用;
四、接收用戶填寫的驗證碼、手機號及其餘註冊數據;
五、對比提交的驗證碼與Session中的驗證碼是否一致,同時判斷提交動做是否在有效期內;
六、驗證碼正確且在有效期內,請求經過,處理相應的業務。jquery

 

前端的頁面git

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>驗證碼使用演示</title>
<link href="<%=basePath%>/css/register.css" rel="stylesheet" >
<script src="<%=basePath%>/js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="<%=basePath%>/js/register.js" type="text/javascript"></script>
<script>
	function getBasePath(){
	    return '<%=basePath%>';
    }
</script>
</head>
<body>
   <form>
       <div class="row">
           <label>帳號: </label><input name="userId">
       </div>
       <div class="row">
           <label>密碼:</label><input name="password">
       </div>
       <div class="row">
           <label>手機號:</label><input name="mobile">
       </div>
       <div class="row">
           <label>驗證碼:</label>
           <input name="verifyCode">
           <button type="button" class="sendVerifyCode">獲取短信驗證碼</button>
       </div>
       <div><button type="button" class="sub-btn">提交</button></div>
   </form>
</body>
</html>

  jsgithub

$(function(){ 
	//短信驗證碼倒計時
	var countdownHandler = function(){
		var $button = $(".sendVerifyCode");
		var number = 60;
		var countdown = function(){
			if (number == 0) {
				$button.attr("disabled",false);
				$button.html("發送驗證碼");
	            number = 60;
	            return;
	        } else {
	        	$button.attr("disabled",true);
	        	$button.html(number + "秒 從新發送");
	        	number--;
	        }
			setTimeout(countdown,1000);
		}
		setTimeout(countdown,1000);
	}
	//發送短信驗證碼
	$(".sendVerifyCode").on("click", function(){
		var $mobile = $("input[name=mobile]");
		var data = {};
		data.mobile = $.trim($mobile.val());
		if(data.mobile == ''){
			alert('請輸入手機號碼');
			return;
		}
		var reg = /^1\d{10}$/;
		if(!reg.test(data.mobile)){
			alert('請輸入合法的手機號碼');
			return ;
		}
		$.ajax({
	        url: getBasePath()+"/sendSms",
	        async : true,
	        type: "post",
	        dataType: "text",
	        data: data,
	        success: function (data) {
	        	if(data == 'success'){
	        		countdownHandler();
	        		return ;
	        	}
	        	alert(data);
	        }
    	});
	})
	//提交
	$(".sub-btn").on("click", function(){
		var data = {};
		data.userId = $.trim($("input[name=userId]").val());
		data.password = $.trim($("input[name=password]").val());
		data.mobile = $.trim($("input[name=mobile]").val());
		data.verifyCode = $.trim($("input[name=verifyCode]").val());
		if(data.userId == ''){
			alert("請輸入帳號");
			return ;
		}
		if(data.password == ''){
			alert("請輸入密碼");
			return ;
		}
		if(data.mobile == ''){
			alert("請輸入手機號");
			return ;
		}
		if(data.verifyCode == ''){
			alert("請輸入驗證碼");
			return ;
		}
		$.ajax({
	        url: getBasePath()+"/register",
	        async : true,
	        type: "post",
	        dataType: "text",
	        data: data,
	        success: function (data) {
	        	if(data == 'success'){
	        		alert("註冊成功");
	        		return ;
	        	}
	        	alert(data);
	        }
    	});
	})
});

  

這裏省略了全部非空、手機號格式驗證ajax

流程:spring

1)填寫手機號

2)獲取手機號碼,調用sendSms.html接口向手機發送短信驗證碼

3)用戶手機接收到驗證碼後,將其填寫到"驗證碼"文本框中

 

後端代碼

發送短信驗證碼

package com.zhenzi.sms;
 
import java.io.IOException;
import java.util.Random;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import com.alibaba.fastjson.JSONObject;
 
/**
 * 獲取驗證碼
 */
public class SendSmsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//短信平臺相關參數
	private String apiUrl = "https://sms_developer.zhenzikj.com";
	private String appId = "000000";
	private String appSecret = "c384b67bdsserev3343cdda4de5c8";
       
    public SendSmsServlet() {
        super();
    }
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
 
	/**
	 * 短信平臺使用的是榛子云短信(smsow.zhenzikj.com)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String mobile = request.getParameter("mobile");
			JSONObject json = null;
			//生成6位驗證碼
			String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			//發送短信
			ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
			String result = "{code:0}";//client.send(mobile, "您的驗證碼爲:" + verifyCode + ",該碼有效期爲5分鐘,該碼只能使用一次!");
			json = JSONObject.parseObject(result);
			if(json.getIntValue("code") != 0){//發送短信失敗
				renderData(response, "fail");
				return; 
			}
			//將驗證碼存到session中,同時存入建立時間
			//以json存放,這裏使用的是阿里的fastjson
			HttpSession session = request.getSession();
			json = new JSONObject();
			json.put("mobile", mobile);
			json.put("verifyCode", verifyCode);
			json.put("createTime", System.currentTimeMillis());
			// 將認證碼存入SESSION
			request.getSession().setAttribute("verifyCode", json);
			renderData(response, "success");
			return ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderData(response, "fail");
	}
	
	protected void renderData(HttpServletResponse response, String data){
		try {
			response.setContentType("text/plain;charset=UTF-8");
			response.getWriter().write(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

json工具使用的是阿里的fastjson

appId和appSecret換成你本身的,註冊以後可得到

註冊地址: http://sms_developer.zhenzikj.com/zhenzisms_user/register.html

 

提交註冊

package com.zhenzi.sms;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.alibaba.fastjson.JSONObject;
 
/**
 * 註冊
 */
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    
    public RegisterServlet() {
        super();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        String mobile = request.getParameter("mobile");
        String verifyCode = request.getParameter("verifyCode");
        JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
        if(json == null){
            renderData(response, "驗證碼錯誤");
            return ;
        }
        if(!json.getString("mobile").equals(mobile)){
            renderData(response, "手機號錯誤");
            return ;
        }
        if(!json.getString("verifyCode").equals(verifyCode)){
            renderData(response, "驗證碼錯誤");
            return ;
        }
        if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
            renderData(response, "驗證碼已過時");
            return ;
        }
        //其餘業務代碼
        renderData(response, "success");
    }
    protected void renderData(HttpServletResponse response, String data){
        try {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ok,大功告成

相關文章
相關標籤/搜索