java實現(xiàn)短信驗證碼5分鐘有效時間
本文實例為大家分享了java實現(xiàn)短信驗證碼5分鐘有效時間,供大家參考,具體內(nèi)容如下
實現(xiàn)一個發(fā)送短信驗證碼的請求,要求5分鐘之內(nèi)重復(fù)請求,返回同一個驗證碼。
網(wǎng)上可找到幾種方案:
如,存儲數(shù)據(jù)庫或緩存中。實現(xiàn)起來比較麻煩,舍棄;
另一種方式即本例,使用session存儲。其他方式,暫未進一步了解。
實現(xiàn)步驟: (springmvc)
1、controller中,獲取session對象,取code,取不到新生成,并存儲session中;
2、單手機號發(fā)送量,判斷并 +1 記入數(shù)據(jù)庫;
3、Timer定時器,設(shè)置新線程延時執(zhí)行TimerTask任務(wù)(刪除code)
@RequestMapping(value = "sendMessage",method = RequestMethod.GET) public Object sendMessage(final HttpServletRequest request){ String phone=request.getParameter("phone"); int times=userService.messageSendToday(phone); //二次驗證,單個手機號每日發(fā)送上限 if(times <= MAX_PER_DAY){ String checkCode=GenerateRandomCode.createRandomNumber(6); final HttpSession httpSession=request.getSession(); httpSession.setAttribute("checkCode",checkCode); CheckCodeMessage checkCodeMessage=new CheckCodeMessage(phone,checkCode); try { HttpSender.batchSend(checkCodeMessage); //TimerTask實現(xiàn)5分鐘后從session中刪除checkCode final Timer timer=new Timer(); timer.schedule(new TimerTask() { @Override public void run() { httpSession.removeAttribute("checkCode"); System.out.println("checkCode刪除成功"); timer.cancel(); } },5*60*1000); } catch (Exception e) { e.printStackTrace(); } return "redirect:/index.jsp"; } }
Timer定時任務(wù):
//TimerTask實現(xiàn)5分鐘后從session中刪除checkCode final Timer timer=new Timer(); timer.schedule(new TimerTask() { @Override public void run() { httpSession.removeAttribute("checkCode"); System.out.println("checkCode刪除成功"); timer.cancel(); } },5*60*1000);
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis-plus foreach拼接字符串查詢無數(shù)據(jù)返回問題
這篇文章主要介紹了Mybatis-plus foreach拼接字符串查詢無數(shù)據(jù)返回問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03Java中String類(字符串操作)的10個常見問題和解決方法
這篇文章主要介紹了Java中String類(字符串)操作的10個常見問題,需要的朋友可以參考下2014-04-04SpringBoot中使用HTTP客戶端工具Retrofit
這篇文章主要為大家介紹了SpringBoot中使用HTTP客戶端工具Retrofit方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06解決springboot配置logback-spring.xml不起作用問題
這篇文章主要介紹了解決springboot配置logback-spring.xml不起作用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11SpringBoot實現(xiàn)阿里云快遞物流查詢的示例代碼
本文將基于springboot實現(xiàn)快遞物流查詢,物流信息的獲取通過阿里云第三方實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2021-10-10