实现一个发送短信验证码的请求,要求5分钟之内重复请求,返回同一个验证码。
网上可找到几种方案:
如,存储数据库或缓存中。实现起来比较麻烦,舍弃;
另一种方式即本例,使用session存储。其他方式,暂未进一步了解
@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定时任务:
//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);
------------------------------------------------------------------------------------------------------------------------------------------欢迎光临,期待您的下次光临!