1. 程式人生 > >基於Maven的Spring+SpringMVC+Hibernate 簡訊驗證碼

基於Maven的Spring+SpringMVC+Hibernate 簡訊驗證碼

因為畢業設計的原因,在做註冊登入時想新增找回密碼功能,想試試看能不能用簡訊驗證的方式,花了一天的終於搞定,總結如下:
先上效果圖,感興趣的再往下看:

(前臺)
這裡寫圖片描述

(後臺)
這裡寫圖片描述

(驗證碼)
這裡寫圖片描述

(驗證成功)
這裡寫圖片描述

1、首先要註冊簡訊平臺,我用的是阿里大於的簡訊服務,因為註冊就送10元代金券,非常適合我這種學生黨和只需畢業設計演示的情況。

2、註冊完成後
這裡寫圖片描述

記住這兩個,後面會用到

這裡寫圖片描述

3、新增簡訊簽名,要通過才能使用
這裡寫圖片描述

4、新增簡訊模板
這裡寫圖片描述

接下來就是開發:

jsp頁面:

<!-- 存放返回的驗證碼 -->
<input type="hidden"
name="keepCode" id="keepCode" value="gzh" />
<div class="form-group" style="display: true;" id="phoneDiv"> <label for="input_phone"> <span class="glyphicon glyphicon-phone"></span>&nbsp; <label for="phone">密保手機</label></label> <input class="form-control input-lg"
id="phone" name="phone" type="text" placeholder="請輸入註冊的密保手機!" value="">
</div>

js

<!-- 獲取輸入值 -->
var phone = $("#phone").val();
<!-- 向controller傳參 -->
var paras = "o_tel=" + phone;
$.post(path + "/message/sendMsg?" + paras,function(data) {
        if (data != null && typeof (data) != "undefined") {
                    var msg = data['code'];
                    <!-- 儲存到隱藏的input -->
$("#keepCode").attr("value", msg); } }, "json");

Controller

@Controller
@RequestMapping("/message")
public class SmsController {
    @ResponseBody
    @RequestMapping(value = "/sendMsg",method = RequestMethod.POST)  
    public String sendMsg(HttpServletRequest request,HttpServletResponse response) throws ClientException {
         String phoneNumber = request.getParameter("o_tel");//獲取前端傳送過來的電話號碼
         String randomNum = createRandomNum(6);//隨機生成6位數的驗證碼
         String jsonContent = "{\"code\":\"" + randomNum + "\"}";//這裡的code對應在阿里大於建立簡訊模板時的${code}
         Map<String, String> paramMap = new HashMap<>();
         paramMap.put("phoneNumber", phoneNumber);
         paramMap.put("msgSign", "簡訊簽名的簽名名稱");//阿里大於建立簡訊簽名的簽名名稱 
         paramMap.put("templateCode", "簡訊模板的    
模版CODE");//阿里大於建立簡訊模板的模版名稱      
         paramMap.put("jsonContent", jsonContent);
         SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap); //阿里大於傳送機制   
         if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
             System.out.println(paramMap);
             System.out.println("簡訊驗正碼傳送成功!");       
         }else {
             System.out.println(sendSmsResponse.getCode()+" 簡訊傳送失敗!");   
         }
        return jsonContent;

        }
        /**
         * 生成隨機數
         * @param num 位數
         * @return
         */
        public static String createRandomNum(int num){
         String randomNumStr = "";
         for(int i = 0; i < num;i ++){
          int randomNum = (int)(Math.random() * 10);
          randomNumStr += randomNum;
         }
         return randomNumStr;
        }
}

阿里大於封裝的

public class AliyunMessageUtil {
    private static final String product = "Dysmsapi";
     //產品域名,開發者無需替換
     private static final String domain = "dysmsapi.aliyuncs.com";
     // 此處需要替換成開發者自己的AK(在阿里雲訪問控制檯尋找)
     private static final String accessKeyId = "你的accessKeyId ";
     private static final String accessKeySecret = "你的accessKeySecret";
     public static SendSmsResponse sendSms(Map<String, String> paramMap) throws com.aliyuncs.exceptions.ClientException {
      //可自助調整超時時間
      System.setProperty("sun.net.client.defaultConnectTimeout", "60000");
      System.setProperty("sun.net.client.defaultReadTimeout", "60000");
      //初始化acsClient,暫不支援region化
      IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
      DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
      IAcsClient acsClient = new DefaultAcsClient(profile);
      //組裝請求物件-具體描述見控制檯-文件部分內容
      SendSmsRequest request = new SendSmsRequest();
      //必填:待發送手機號
      request.setPhoneNumbers(paramMap.get("phoneNumber"));
      //必填:簡訊簽名-可在簡訊控制檯中找到
      request.setSignName(paramMap.get("msgSign"));
      //必填:簡訊模板-可在簡訊控制檯中找到
      request.setTemplateCode(paramMap.get("templateCode"));
      //可選:模板中的變數替換JSON串,如模板內容為"親愛的${name},您的驗證碼為$[code]"時,此處的值為
      request.setTemplateParam(paramMap.get("jsonContent"));
      //選填-上行簡訊擴充套件碼(無特殊需求使用者請忽略此欄位)
    //  request.setSmsUpExtendCode(paramMap.get("extendCode"));
      //可選:outId為提供給業務方擴充套件欄位,最終在簡訊回執訊息中將此值帶回給呼叫者
    //  request.setOutId(paramMap.get("outId"));
      //hint 此處可能會丟擲異常,注意catch
      SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
      return sendSmsResponse;
     }
}

全部結束