验证码---短信验证码

青旅半醒 2022-01-09 08:53 751阅读 0赞

最近自学了短信的验证码实现。以下是自己用的一种方法实现的完整的过程。

短信验证登陆(前端+后台)

1、前端填写手机号以及点击触发,以电话号码为参数调用发送验证登录短信方法并在前端产生随机数存于Seesion 中,将手机号连同产生的随机数发送到后台操作(已经设置好缓存存放时间)

2、调用发送模板短信方法发送短信(设置好短信中验证码有效的时间)

3、点击触发登陆,调用对应验证登录函数 ,以电话号码和验证码为参数

4、校验缓存中对应保留的信息
如果一致,登陆成功;
登陆不成功是返回原因(1、超时 2、验证码输入错误)

实现:

我的实现是利用网易云信实现的。

  1. 注册网易云信

  2. 创建IM 应用

  3. 一般首次注册会有免费的短信条数,不用去购买

  4. 创建一个短信模板,等待审核

  5. 在自己创建的IM 应用中找到 App Key管理把相应的Appkey和appSecret放入到代码中

由于使用的网易云信得短信验证故无法得知他把我们获取到的验证码放置在了何处,故在这里的校验验证码我们也只能交给网易云信来判断,我们只能对写出后台代码来传送给网易云信,主要是若想真正的实现验证我们需要一个api的接口来实现。

下面是一个简单的短信验证的例子(包括了对短信获取到的验证码的验证)

1、 前端代码(html)

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>短信验证码实现</title>
  8. <link rel="stylesheet" href="css/bootstrap.css">
  9. <link rel="stylesheet" href="css/_phone.css">
  10. <script type="text/javascript" src="js/jquery.js"></script>
  11. <script type="text/javascript" src="js/bootstrap.js"></script>
  12. <script type="text/javascript" src="js/_phone.js"></script>
  13. </head>
  14. <body>
  15. <div id="bodys">
  16. <div id="top">
  17. <div id="left">
  18. 手机号:<input type="text" id="phoneNum" name="phone" οnblur="checkNum()" value="${phone }">
  19. </div>
  20. <div id="right">
  21. <input type="text" id="errormessage" style="display: none;">
  22. </div>
  23. </div>
  24. <div id="foot">
  25. 验证码:<input type="text" id="confirmNum" οnclick="checkCode()">
  26. <input type="hidden" id="test" value="${phone }+${number }">
  27. <input type="button" class="btn-primary" value="获取验证码" name="number" id="gettime">
  28. </div>
  29. <div id="tool">
  30. <input type="submit" class="btn-primary" value="登陆" οnclick="logins()">
  31. </div>
  32. </div>
  33. </body>
  34. </html>
  1. 前端代码(jsp+css)

    /检查手机号是否正确/

    function checkNum() {

    1. if ($("#phoneNum").val() == null || $("#phoneNum").val() == "") {
    2. $("#errormessage").css({
    3. "display" : "block",
    4. "border" : "none",
    5. "color" : "red"
    6. });
    7. $("#errormessage").val("手机号不能为空!");
    8. } else if (!(/^1[3|5|8|4][0-9]\d{
    9. 4,8}$/.test($("#phoneNum").val()))) {
    10. /* 正则表达式判断手机号是否符合标准 */
    11. $("#errormessage").css({
    12. "display" : "block",
    13. "border" : "none",
    14. "color" : "red"
    15. });
    16. $("#errormessage").val("手机号格式不对!");
    17. } else {
    18. $("#errormessage").css({
    19. "display" : "block",
    20. "border" : "none",
    21. "color" : "green"
    22. });
    23. $("#errormessage").val("√");
    24. }

    }

    //先随机产生4位数字,保存到数据库,然后发送到手机上

    var number;

    // 倒计时

    var time = 61;

    var t;

    // 获取验证码

    $(document).ready(function() {

    1. $('#gettime').click(function() {
    2. // 先随机产生4位数字,保存到数据库,然后发送到手机上
    3. number = Math.floor(Math.random() * 9000) + 1000;
    4. t = setInterval("gettime()", 1000);
    5. var phone = $("#phoneNum").val(); location.href="MessageSend?&phone="+$("#phoneNum").val()+"&number="+$("confirmNum").val(); alert(number+"-------"+phone);
    6. })

    })

    /修改时间,即在时间段内没有获取到/

    function gettime() {

    1. time--;
    2. if (time > 0) {
    3. $('#gettime').val(time + 's');
    4. $('#gettime').css("color", "red");
    5. } else {
    6. $('#gettime').val('重新获得验证码');
    7. $('#gettime').css("color", "red");
    8. t = clearInterval(t);/* 清楚时间重新获取 */
    9. time = 61;
    10. }

    }

    /将填写的数据传送到servlet中/

    function logins(){

    1. location.href="MessageCheck?&phone="+$("#phoneNum").val()+"&checknum="+$("confirmNum").val();

    }

    CSS

    bodys{ margin:200px auto 0px; width:450px;}

    top { height: 40px; }

    top #left{ float: left; }

    top #right{ float: right; }

    top input{ width:200px; }

    foot{ position: relative; top: 10px; }

    tool{ position: relative; top: 10px; }

3.发送验证码(java)

  1. package com.mobile;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.Date;
  5. import java.util.List;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.message.BasicNameValuePair;
  18. import org.apache.http.util.EntityUtils;
  19. import com.alibaba.fastjson.JSON;
  20. @WebServlet("/MessageSend")
  21. public class MessageSend extends HttpServlet {
  22. private static final long serialVersionUID = 1L;
  23. private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";// 发送验证码的请求路径URL
  24. private static final String APP_KEY = "0b4828b25c0**************c41";// 网易云信分配的账号
  25. private static final String APP_SECRET = "5***97";// 网易云信分配的密钥
  26. private static final String NONCE = "123456";// 随机数
  27. public MessageSend() {
  28. super();
  29. // TODO Auto-generated constructor stub
  30. }
  31. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  32. throws ServletException, IOException {
  33. request.setCharacterEncoding("utf-8");
  34. response.setHeader("Context-type", "text/html;Charset=utf-8");
  35. String phone = request.getParameter("phone");
  36. String number = request.getParameter("number");
  37. //将数据再次返回给页面显示
  38. request.setAttribute("phone", phone);
  39. request.setAttribute("number", number);
  40. System.out.println( "phone:---"+request.getParameter("phone"));
  41. sendMsg(phone);
  42. request.getRequestDispatcher("Phone.jsp").forward(request, response);
  43. }
  44. public static String sendMsg(String phone) throws IOException {
  45. CloseableHttpClient httpclient = HttpClients.createDefault();
  46. HttpPost post = new HttpPost(SERVER_URL);
  47. String curTime=String.valueOf((new Date().getTime()/1000L));
  48. String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);
  49. //设置请求的header
  50. post.addHeader("AppKey",APP_KEY);
  51. post.addHeader("Nonce",NONCE);
  52. post.addHeader("CurTime",curTime);
  53. post.addHeader("CheckSum",checkSum); post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  54. //设置请求参数
  55. List<NameValuePair> nameValuePairs =new ArrayList<>();
  56. nameValuePairs.add(new BasicNameValuePair("mobile",phone));
  57. post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
  58. //执行请求
  59. HttpResponse response=httpclient.execute(post);
  60. String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
  61. //判断是否发送成功,发送成功返回true
  62. String code= JSON.parseObject(responseEntity).getString("code");
  63. if (code.equals("200")){
  64. return "success";
  65. }
  66. return "error";
  67. }
  68. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  69. throws ServletException, IOException {
  70. // TODO Auto-generated method stub
  71. doGet(request, response);
  72. }
  73. }

4 验证短信验证码

  1. com.mobile;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.Date;
  5. import java.util.List;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.message.BasicNameValuePair;
  18. import org.apache.http.util.EntityUtils;
  19. import com.alibaba.fastjson.JSON;
  20. /**
  21. * Servlet implementation class MessageCheck
  22. */
  23. @WebServlet("/MessageCheck")
  24. public class MessageCheck extends HttpServlet {
  25. private static final long serialVersionUID = 1L;
  26. private static final String SERVER_URL = "https://api.netease.im/sms/verifycode.action";// 校验验证码的请求路径URL
  27. private static final String APP_KEY = "0b482******1";// 网易云信分配的账号
  28. private static final String APP_SECRET = "5*****97";// 网易云信分配的密钥
  29. private static final String NONCE = "123456";// 随机数
  30. /**
  31. * @see HttpServlet#HttpServlet()
  32. */
  33. public MessageCheck() {
  34. super();
  35. // TODO Auto-generated constructor stub
  36. }
  37. /**
  38. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  39. * response)
  40. */
  41. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  42. throws ServletException, IOException {
  43. request.setCharacterEncoding("utf-8");
  44. response.setHeader("Context-type", "text/html;Charset=utf-8");
  45. String phone = request.getParameter("phone");
  46. String checknum = request.getParameter("checknum");
  47. checkMsg(phone,checknum);
  48. request.getRequestDispatcher("index.jsp").forward(request, response);
  49. }
  50. public static String checkMsg(String phone,String sum) throws IOException {
  51. CloseableHttpClient httpclient = HttpClients.createDefault();
  52. HttpPost post = new HttpPost(SERVER_URL);
  53. String curTime=String.valueOf((new Date().getTime()/1000L));
  54. String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);
  55. //设置请求的header
  56. post.addHeader("AppKey",APP_KEY);
  57. post.addHeader("Nonce",NONCE);
  58. post.addHeader("CurTime",curTime);
  59. post.addHeader("CheckSum",checkSum);
  60. post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  61. //设置请求参数
  62. List<NameValuePair> nameValuePairs =new ArrayList<>();
  63. nameValuePairs.add(new BasicNameValuePair("mobile",phone));
  64. nameValuePairs.add(new BasicNameValuePair("code",sum));
  65. post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
  66. //执行请求
  67. HttpResponse response=httpclient.execute(post);
  68. String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
  69. //判断是否发送成功,发送成功返回true
  70. String code= JSON.parseObject(responseEntity).getString("code");
  71. if (code.equals("200")){
  72. return "success";
  73. }
  74. return "error";
  75. }
  76. /**
  77. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  78. * response)
  79. */
  80. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  81. throws ServletException, IOException {
  82. // TODO Auto-generated method stub
  83. doGet(request, response);
  84. }
  85. }

至此便可以实现短信的验证码

转载于:https://www.cnblogs.com/sunny-su/p/10643399.html

发表评论

表情:
评论列表 (有 0 条评论,751人围观)

还没有评论,来说两句吧...

相关阅读

    相关 验证---验证

    最近自学了短信的验证码实现。以下是自己用的一种方法实现的完整的过程。 短信验证登陆(前端+后台) 1、前端填写手机号以及点击触发,以电话号码为参数调用发送验证登录短信方法并