服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java短信验证码获取次数限制实例

java短信验证码获取次数限制实例

2021-03-15 13:32韩语 Java教程

这篇文章主要介绍了java短信验证码获取次数限制实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

现在不管什么项目,用到短信验证功能,都会在程序上设计一个短信验证码的获取次数限制,这样主要是避免短信验证码接口被刷。

前一段正好做一个项目的用户短信验证码登录功能,就研究了以下,下面贴出来分享一下。

这里涉及到的短信接口,用的第三方短信接口—动力思维思维乐信的(http://www.lx598.com/),如果想了解短信接口接入,可以到他们官网,查看下短信接口API文档说明,参考下面的代码应该就能弄明白。

用户注册部分,主要代码如下:

java" id="highlighter_6621">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//主要js方法:
 
//获取手机验证码:
 
function getRegCode() {
    if($.trim($('#inputCaptcha').val()) == ''){
       $('#imgRs').html("图形验证码不能为空");
       $('#inputCaptcha').select();
       return;
     }
    
    if (!isPhoneNum($('#phoneRe').val())) {
      document.getElementById('phoneReInfo').innerHTML = '<font color="red">请填写有效的11位手机号码</font>';
    } else {
      document.getElementById('phoneReInfo').innerHTML = '注册后用手机号码进行登录';
    
 
      $.ajax({
        url : "${path}/account/checkMob",
        type : "POST",
        data : "account.ACCMOB=" + $('#phoneRe').val(),
        contentType : "application/x-www-form-urlencoded;charset=utf-8",
        async : false,
        success : function(data) {
          res = data;
          if (data == 1) {
            document.getElementById('phoneReInfo').innerHTML = '<font color="red">该手机号已被注册</font>';
            refreshYzm();
          } else {
            document.getElementById('phoneReInfo').innerHTML = '<font color="green">该手机号可用</font>';
            $.ajax({
              url : "${path}/account/reAimcodeGetVeCode",
              type : "POST",
              data : "account.ACCMOB="
                  + $('#phoneRe').val()
                  + "&fromSource=4&smsCount="+$('#smsCount').val()
                  +"&searchName="+$.trim($('#inputCaptcha').val()),
              contentType : "application/x-www-form-urlencoded;charset=utf-8",
              async : false,
              success : function(data) {
                myArray = data.split("&");
                if (myArray[0] == '发送成功!') {
                  canCaptcha = true;
                  document.getElementById('phoneReInfo').innerHTML = '<font color="green">验证码已发送,请注意查收!</font>
                  accountFID = myArray[1];
                  }else if(data == '限制申请'){
                  document.getElementById('phoneReInfo').innerHTML = '<font color="red">一个手机号码一天最多只能申请3次!</font>';
                  refreshYzm();
                }else if(data == '验证码错误'){
                  document.getElementById('phoneReInfo').innerHTML = '<font color="red">验证码错误!</font>';
                  refreshYzm();
                }
              },
              error : function() {
                alert('异常,内部验证出错!'+data);
              }
            });
 
          }
        },
              error : function() {
              alert('异常,验证出错!');
            }
          });
    }
    var smsCount=parseInt($('#smsCount').val());
    smsCount=smsCount<3?smsCount+1:3;
    $('#smsCount').val(smsCount);
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// 注册新用户
// account 为用户类
 
  @Action(value = "reAimcodeGetVeCode")
  public void reAimcodeGetVeCode() {
    PrintWriter out;
    String result = "验证码申请失败!请重试!";
    try {
      smsUnit = new SmsUnit(ConfUtil.getProperty("sys_sms_server"));
      if (null != account.getACCMOB() && !account.getACCMOB().equals("")) {
        account.setACCSTATUS(new BigDecimal(1));//设置使用状态:未用
        String verifyCode = String
            .valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码
        account.setFSECURITYCODE(verifyCode);
        account.setACCCREATEDATE(new Date());
        
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1); // 设置验证码失效时间为24小时
        account.setFREGISTERSOURCE(fromSource);//设置注册来源
        // 判断该手机是否获取过验证码
        AccountCriteria accountCriteria = new AccountCriteria();
        accountCriteria.createCriteria().andACCMOBEqualTo(
            account.getACCMOB());
        List<Account> accs = accountService
            .selectByExample(accountCriteria);
        //验证码申请次数
        int re = 0;
        Integer cishu = 0;
        //如果用户不存在
        if (accs == null || accs.isEmpty()) {
          cishu = 1;
          account.setSDKURL("1");
          account.setFSECURITYOUTTIME(c.getTime());//设置验证码有效时间
          BigDecimal accid=accountService.getPrimaryKey();
          account.setFID(accid);
          re = accountService.insertSelective(account,IPUtil.getRealIP(request));
          Cookie cookie=new Cookie("id" , accid.toString());
          cookie.setMaxAge(Integer.MAX_VALUE);
          response.addCookie(cookie);
        } else {
          Account ac = accs.get(0);
          account.setFID(ac.getFID());
          Date date = new Date();
          // 通过时间判定申请验证码次数
          //如果是新的一天,则使用次数改为1
          if (date.getDate() >= ac.getFSECURITYOUTTIME().getDate()) {
            account.setSDKURL("1");
          } else {
            Integer count = Integer.parseInt(ac.getSDKURL());
            account.setSDKURL(count + 1 + "");//不是新的一天则次数+1
          }
          cishu = Integer.parseInt(account.getSDKURL());
          account.setFSECURITYOUTTIME(c.getTime());
          if (cishu <= 3)
            re = accountService
                .updateByPrimaryKeySelective(account); //使用修改方法保存验证码发送信息
        }
 
        if (re > 0 && cishu <= 3) {
          request.getSession().removeAttribute(ConstValues.WEB_SESSION_PROMOTE);
          AccountCriteria ac = new AccountCriteria();
          ac.createCriteria().andACCMOBEqualTo(account.getACCMOB());
          List<Account> acList = new ArrayList<Account>();
          acList = accountService.selectByExample(ac);
          if (acList != null && acList.size() > 0) {
            // 这里执行短信发送
            
            String content = "您的验证码为:" + verifyCode+",该码有效期为24小时,该码只能使用一次!【短信签名】";
            SendSmsReply sendSmsReply = smsUnit.sendSms(accName,accPwd ,account.getACCMOB(),content,"");
 
//调用第三方接口发送短信            result = sendSmsReply.getReplyMsg() + "&"
                + acList.get(0).getFID() + "&"
                + acList.get(0).getSDKURL();
          }
        } else if (cishu > 3) {
          result = "限制申请";
        }
      }
    } catch (Exception e) {
      logger.error("获取验证码失败", e);
    } finally {
      try {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        out = response.getWriter();
        out.write(result);
      } catch (IOException e) {
        logger.error("", e);
      }
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//这是动力思维乐信第三方短信接口的发送短信功能部分参考代码:
 
/**
         * 发送短信
         * @param accName 乐信账号用户名
         * @param accPwd 乐信账号密码
         * @param seed 当前时间 格式:YYYYMMDD HHMISS 例如:20130806102030
         * @param aimcodes 手机号多个手机号之间英文半角逗号隔开
         * @param content 内容后加签名
         * @param schTime 定时时间格式如:2010-01-01 08:00:00
         * @return 服务端返回的结果 ok:业务id 或者 错误代码
         */
        public static String sendSms(String accName,String accPwd,String mobies,String content,String schTime){
          StringBuffer sb = new StringBuffer("http://sdk.lx198.com/sdk/send2?");
          try {
            String seed=new SimpleDateFormat(dateFormatStr).format(new Date());
            sb.append("&accName="+accName);
            sb.append("&seed="+seed);
            sb.append("&accPwd="+MD5.getMd5String(MD5.getMd5String(accPwd)+seed));
            sb.append("&aimcodes="+mobies);
            sb.append("&schTime="+URLEncoder.encode(schTime,"UTF-8")); //空格标点符号做encode转换
            sb.append("&content="+URLEncoder.encode(content,"UTF-8")); //中文做encode转换
            URL url = new URL(sb.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            return in.readLine();
          } catch (Exception e) {
            e.printStackTrace();
          }
          return null;
        }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000012714481

延伸 · 阅读

精彩推荐