为什么要限制一分钟之内只能发送一次手机短信呢?
防止恶意攻击.
什么场景需要发送手机短信?
(a)手机号注册
(b)通过手机找回密码
(c)手机号绑定,手机号换绑
(d)转账时手机号接收动态口令(一次一密)
1,前端
一般前端会有倒计时,在倒计时的过程中是不允许点击"发送短信"按钮的:
但是如果用户刷新页面呢?
如果刷新页面,那么页面的倒计时就会中断.
这是需要服务器端提供支持:服务器端要记录上次发送短信的时间戳
2,后台
第一次发送时lastSendSMSTime 为null,于是设置当前时间A,说明不需要倒计时 第二次访问时,lastSendSMSTime 不为null,获取其值,为时间A; 同时获取当前时间B,计算时间A,和时间B 的差量delter. 业务逻辑是:拿delter和60进行比较,如果delter>60,说明两次发短信的时间相差60秒,则允许发送,会重置时间为当前时间; 若delter<=60秒,则不允许发送,并且不会重置时间
|
后台获取倒计时剩余时间的方法:
/*** * 倒计时还剩余多长时间 * @param mobile : 手机号 * @param reallySendSMS : 是否真正发送短信 * @return : second */ public int sMSWaitingTime(String mobile,boolean reallySendSMS) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); RedisHelper rdsHelper = RedisHelper.getInstance(); String cid = getCid(request, response); String lastSendSMSTime = rdsHelper.getCache(cid+mobile); if(StringUtil.isNullOrEmpty(lastSendSMSTime)) { if(reallySendSMS){ saveExpxKeyCache(request, response, mobile, String.valueOf(DateTimeUtil.getCurrentTimeSecond()),60); } return 0;//不需要倒计时 } else { long lastSendSMSTimeSecond=Long.parseLong(lastSendSMSTime); long currentTimeSecond=DateTimeUtil.getCurrentTimeSecond(); int delter=(int) (currentTimeSecond-lastSendSMSTimeSecond); if(delter>=60){ return 0;//不需要倒计时 }else{ return 60-delter; } } }
接口:
/** * @return {"result":true,"remainingSecond":39}<br> * {"result":false,"errorFieldName":"mobile","remainingSecond":0} * @api {get} /wap/countdownSMS 发送手机短信倒计时剩余时间 * @apiName 发送手机短信倒计时剩余时间 * @apiGroup Login * @apiVersion 1.0.0 * @apiDescription 发送手机短信倒计时剩余时间 * @apiPermission 无权限要求 * @apiParam {String} mobile 手机号 */ @SessionCheck @RequestMapping("/countSMS") @ResponseBody public String countdownSMS(HttpSession httpSession, HttpServletRequest request , String mobile) { SMSRemainingTimeDto dto = new SMSRemainingTimeDto(); if (StringUtil.isNullOrEmpty(mobile)) { dto.setResult(false); dto.setErrorFieldName("mobile"); dto.setErrorMessage("请输入手机号"); return dto.toJson(); } else { int remainingTime = sMSWaitingTime(mobile, false); dto.setResult(true); dto.setRemainingSecond(remainingTime); return dto.toJson(); } }
接口功能:返回倒计时的剩余秒数
3,什么时候调用该接口呢?
(1)手机号输入框失去焦点时;
(2)页面加载完成时,判断手机号输入框是否有值,有值就调用.
window.onload 或者jquery的$(function)