This example shares with you the 5-minute validity time for Java SMS verification code for your reference. The specific content is as follows
Implement a request to send a SMS verification code, requiring repeated requests within 5 minutes and return the same verification code.
Several solutions can be found online:
For example, storage database or cache. It is more troublesome to implement, give up;
Another way is this example, using session storage. Other methods are not yet understood.
Implementation steps: (springmvc)
1. In the controller, get the session object, get the code, and cannot get the new generation, and store the session;
2. The number of sending a single mobile phone number is judged and recorded in the database +1;
3. Timer timer, set the new thread to delay execution of TimerTask tasks (delete code)
@RequestMapping(value = "sendMessage",method = RequestMethod.GET)public Object sendMessage(final HttpServletRequest request){ String phone=request.getParameter("phone"); int times=userService.messageSendToday(phone); //Second verification, a single mobile phone number sends a daily limit 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 is implemented for 5 minutes and deleted from the session final Timer timer=new Timer(); timer.schedule(new TimerTask() { @Override public void run() { httpSession.removeAttribute("checkCode"); System.out.println("checkCode deleted successfully"); timer.cancel(); } },5*60*1000); } catch (Exception e) { e.printStackTrace(); } return "redirect:/index.jsp"; }}Timer timing tasks:
//TimerTask is implemented for 5 minutes and deleted from the session checkCodefinal Timer timer=new Timer();timer.schedule(new TimerTask() { @Override public void run() { httpSession.removeAttribute("checkCode"); System.out.println("checkCode deleted successfully"); timer.cancel(); }}, 5*60*1000);The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.