Spring MVC 中 簡訊驗證碼功能的實現方法_java

來源:互聯網
上載者:User

在外部網站中簡訊的驗證很有必要,比如在實現註冊、驗證使用者資訊等的情況下。在SpringMVC中的實現如下:

簡訊介面

簡訊介面,有些企業會購買的有移動的簡訊平台介面。如果是個人或者是小企業可以使用一些雲端服務的。比如百度的API Store上面的。

我使用的是:http://apistore.baidu.com/apiworks/servicedetail/1018.html

當然簡訊介面肯定都是要付費的,而且是基於模板的,具體的使用說明可以看這個網址裡面的使用說明。

前端介面

前端的介面,可能如下,點擊擷取驗證碼,然後按鈕變為灰色並且倒計時。(手機號是我的~~)

HTML代碼就不寫了,JS如下:vailidationCode是擷取驗證碼按鈕的ID。phone是手機號碼的ID,手機號碼只是簡單的驗證了,如果是要更精確,使用正則,其中的url的sendSms是背景springMVC的路徑。

$("#validationCode").click(function(){var phone = $("#phone").val();if($("#phone").val() && $("#phone").val().length == 11){$.ajax({cache : false,url : "sendSms",data : {phone : phone}});updateButtonStatus();}else {alert("請輸入合法的手機號");}});var countdown=60;function updateButtonStatus(){var phone = $("#validationCode");if (countdown == 0) {phone.attr("disabled","false");phone.val("免費擷取驗證碼");countdown = 60;return;} else {phone.attr("disabled","true");phone.val("重新發送(" + countdown + ")");countdown--;}setTimeout(function() {updateButtonStatus() },1000)}

後端代碼

@RequestMapping(value = "/sendSms")@ResponseBodypublic String sendSMS(@RequestParam("phone") String phone, HttpServletRequest request){StringBuilder code = new StringBuilder();Random random = new Random();// 產生6位驗證碼for (int i = 0; i < 6; i++) {code.append(String.valueOf(random.nextInt(10)));}HttpSession session = request.getSession();session.setAttribute(VALIDATE_PHONE, phone);session.setAttribute(VALIDATE_PHONE_CODE, code.toString());session.setAttribute(SEND_CODE_TIME, new Date().getTime());String smsText = "您的驗證碼是:"+code;SMSUtil.send(phone,smsText);return "success";}

其中的SMSUtil是封裝的上面的簡訊介面的發送類。參考如下,其中的API_KEY改成自己的。

public class SMSUtil {static String httpUrl = "http://apis.baidu.com/kingtto_media/106sms/106sms";final static String API_KEY = "xxxx";public static String send(String phone,String content) {BufferedReader reader = null;String result = null;StringBuffer sbf = new StringBuffer();try {String httpArg = "mobile="+phone+"&content="+URLEncoder.encode(content,"UTF-8")+"&tag=2";httpUrl = httpUrl + "?" + httpArg ;URL url = new URL(httpUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 填入apikey到HTTP headerconnection.setRequestProperty("apikey",API_KEY);connection.connect();InputStream is = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();result = sbf.toString();} catch (Exception e) {e.printStackTrace();}return result;}}

前台的表單提交前還需要使用ajax做一下表單的驗證,驗證一下驗證碼是否正確:

@RequestMapping("/validate")@ResponseBodyprotected String validate(HttpServletRequest request,@RequestParam("phone") String inputPhone,@RequestParam ("code") String inputCode){HttpSession session = request.getSession();String code = (String) session.getAttribute(VALIDATE_PHONE_CODE);String phone = (String) session.getAttribute(VALIDATE_PHONE);if(phone.equals(inputPhone) && code.equalsIgnoreCase(inputCode)){return "success";}else{return "failure";}}

以上所述是小編給大家介紹的Spring MVC 中 簡訊驗證碼功能的實現方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.