本文實例為大家分享了java實現手機短信驗證的具體代碼,供大家參考,具體內容如下
整體流程:
通過后,需要將session中的驗證碼無效化,一般就是置為空。
第一步偽代碼:
function sendCaptcha(tel) { console.log("sendCaptcha: tel = " + tel); $.ajax({ type: 'post', url: '/sms/captcha/' + tel, dataType: "json", success: function (data) { console.log("sendCaptcha ==> success: data = " + eval(data)); if (data) { countdown(); b_code = false; } else { alert("您發送的頻率過快!"); } }, error: function (data) { console.log("sendCaptcha ==> error: data = " + eval(data)); alert("網絡超時"); clearTimeout(t); b_code = true; var msg = "獲取驗證碼"; $("#code").text(msg); c = 60; } }); }
第二步偽代碼:
@RequestMapping(value = "captcha/{recPhoneNum}", method = RequestMethod.POST) public Object getSmsCaptcha(ModelMap model, @PathVariable("recPhoneNum")String recPhoneNum) { String responseBody = null; /* 這里驗證手機號是否被注冊 */ ? // 生成驗證碼 String captcha = Generator.generateCaptcha(); ? // 第三方短信通信接口參數設置 req.setReceive(recPhoneNum); try { ? // 發送請求 responseBody = req.send(); // 將驗證碼放入session model.addAttribute("captcha", captcha); ? ? // 得到結果 responseBody = rsp.getBody(); log.debug("getSmsCaptcha: responseBody = " + responseBody); if (rsp.getResult() != null) { model.addAttribute("success_response", rsp.getResult()); } else { model.addAttribute("error_response", rsp.getSubMsg()); } } catch (ApiException e) { log.error("getSmsCaptcha :" + e.getErrMsg()); } // 解析結果 if (successJson != null) { successJson = successJson.getJSONObject("result"); return successJson.getBoolean("success"); } else { return false; } }
最后一步偽代碼:
// 從session取出驗證碼String captcha = session.getAttribute("captcha");// 比較if (reqCaptcha.equals(captcha))// 相同通過,則無效化驗證碼session.setAttribute("captcha", null);else// 不通過并提示無效驗證碼
如有疑問,請指出!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選