为了账号安全,请及时绑定邮箱和手机立即绑定

Java如何实现五分钟内重复获取返回同一个短信验证码

标签:
Java

短信验证码功能是当今网站都需要用到的,最近很多同学反映不会java开发短信验证码功能,今天小编就带大家整理一下Java关于Java实现短信验证码5分钟有效时间返回相同验证码,下面我们一起来看一下吧。

​  实现一个发送短信验证码的请求,要求5分钟之内重复请求,返回同一个验证码。

如存储数据库或缓存中。实现起来比较麻烦,舍弃;另一种方式即本例,使用session存储。其他方式,暂未进一步了解。

完整源码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//发送手机号码
			String mobile = request.getParameter("mobile");
			
			//6位验证码
			String verifyCode = null;
			
			HttpSession session = request.getSession();
			JSONObject json = (JSONObject)session.getAttribute("json");
			if(json == null){
				json = new JSONObject();
				json.put("mobile", mobile);
				verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
				json.put("verifyCode", verifyCode);
				json.put("createTime", System.currentTimeMillis());
				session.setAttribute("json", json);
			}else{
				verifyCode = json.getString("verifyCode");
				long createTime = json.getLong("createTime");
				if((System.currentTimeMillis() - createTime) > 1000 * 60 * 1){//超过5分钟重新生成验证码
					verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
					json.put("verifyCode", verifyCode);
					json.put("createTime", System.currentTimeMillis());
				}
			}
			//发送短信
			//使用的是榛子云短信(http://smsow.zhenzikj.com/doc/sdk.html)
			ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "appId", "appSecret");
			String result = client.send(mobile, "您的验证码为:" + verifyCode + ",该码有效期为5分钟,该码只能使用一次!");
			System.out.println(verifyCode);
			
			response.getWriter().append("success");
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().append("fail");
		}
	}

将要存放到session中的信息放到一个json对象中,然后把这个json对象存入session。当然,你也可以自己封装一个对象,存放mobile、verifyCode、createTime。

短信平台用的是,榛子云短信

下载完整源码: 下载

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
3
获赞与收藏
49

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消