本文實例為大家分享了java實現短信驗證碼5分鐘有效時間,供大家參考,具體內容如下
實現一個發送短信驗證碼的請求,要求5分鐘之內重復請求,返回同一個驗證碼。
網上可找到幾種方案:
如,存儲數據庫或緩存中。實現起來比較麻煩,舍棄;
另一種方式即本例,使用session存儲。其他方式,暫未進一步了解。
實現步驟: (springmvc)
1、controller中,獲取session對象,取code,取不到新生成,并存儲session中;
2、單手機號發送量,判斷并 +1 記入數據庫;
3、timer定時器,設置新線程延時執行timertask任務(刪除code)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
@requestmapping (value = "sendmessage" ,method = requestmethod.get) public object sendmessage( final httpservletrequest request){ string phone=request.getparameter( "phone" ); int times=userservice.messagesendtoday(phone); //二次驗證,單個手機號每日發送上限 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實現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定時任務:
1
2
3
4
5
6
7
8
9
10
|
//timertask實現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 ); |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_37878879/article/details/77585022