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

本文介绍了一种使用Java的TimerTask实现在5分钟后从session中自动移除短信验证码的方法,该方法适用于五分钟内重复请求返回同一验证码的场景。文章还讨论了如何在Spring MVC环境下通过controller获取session、生成验证码并发送,同时利用计时器来控制验证码的有效期。
部署运行你感兴趣的模型镜像
//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";
    }
}

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值