实现短信验证码设置有效时长

//TimerTask实现5分钟后从session中删除code
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    httpSession.removeAttribute("code");
                    timer.cancel();
                }
            },5*60*1000);

实现一个发送短信验证码的请求,要求5分钟之内重复请求,返回同一个验证码。 
网上可找到几种方案: 
如,存储数据库或缓存中。实现起来比较麻烦,舍弃; 
另一种方式即本例,使用session存储。其他方式,暂未进一步了解。

实现步骤:(springmvc) 
1、controller中,获取session对象,取code,取不到新生成,并存储session中; 
2、单手机号发送量,判断并 +1 记入数据库; 
2、Timer定时器,设置新线程延时执行TimerTask任务(删除code)

@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("code",checkCode);
        CheckCodeMessage checkCodeMessage=new CheckCodeMessage(phone,code);
        try {
            HttpSender.batchSend(checkCodeMessage);
            //TimerTask实现5分钟后从session中删除code
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    httpSession.removeAttribute("code");
                    System.out.println("code删除成功");
                    timer.cancel();
                }
            },5*60*1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/index.jsp";
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值