短信验证码的实现及代码案例

首先使用maven搭建web项目导入一下servlet依赖

 <!-- servlet依赖的jar包start -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!-- servlet依赖的jar包start -->
    <!-- jsp依赖jar包start -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <!-- jsp依赖jar包end -->
    <!--jstl标签依赖的jar包start -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--jstl标签依赖的jar包end -->

进入网站下载api文档如图 点击下载
https://www.ihuyi.com/api/sms.html
在这里插入图片描述
解压之后目录为如图
在这里插入图片描述
点击DEMO进入 如图
在这里插入图片描述
点击jsp如图显示:
在这里插入图片描述
把jquery.js放入js文件夹下
第一步百度搜索互亿无线注册会有十条免费的短信验证码
APIID APIKEY 这两个是关键要记住 如图在此处
在这里插入图片描述

编写UserInfo.java代码

package demo4.servlet;

/**
 * package_name:demo4.servlet
 * Author:徐亚远
 * Date:2020/2/13 13:19
 * 项目名:code-projects
 * Desription:
 **/
public class UserInfo {
    public static String account = "APIID";  //APPID此处填写你的APPID是一串数字
    public static String password = "APIKEY";  //APIKEY此处填写你的APIKEY是一串数字
}

编写生成验证码的类 MobileCode.java

package demo4.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * package_name:demo4.servlet
 * Author:徐亚远
 * Date:2020/2/13 13:25
 * 项目名:code-projects
 * Desription:
 **/
public class MobileCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 接口类型:互亿无线触发短信接口,支持发送验证码短信、订单通知短信等。
        // 账户注册:请通过该地址开通账户http://sms.ihuyi.com/register.html
        // 注意事项:
        //(1)调试期间,请使用用系统默认的短信内容:您的验证码是:【变量】。请不要把验证码泄露给其他人。;
        //(2)请使用APIID(查看APIID请登录用户中心->验证码短信->产品总览->APIID)及 APIkey来调用接口;
        //(3)该代码仅供接入互亿无线短信接口参考使用,客户可根据实际需要自行编写;

        String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000); //获取随机数
        req.getSession().setAttribute("valiCode", mobile_code);

        String account = UserInfo.account; //查看用户名是登录用户中心->验证码短信->产品总览->APIID
        String password = UserInfo.password;  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
        String mobile = req.getParameter("mobile");
        String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");
        try {

            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);//允许连接提交信息
            connection.setRequestMethod("POST");//网页提交方式“GET”、“POST”
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Connection", "Keep-Alive");
            StringBuffer sb = new StringBuffer();
            sb.append("account=" + account);
            sb.append("&password=" + password);
            sb.append("&mobile=" + mobile);
            sb.append("&content=" + content);
            OutputStream os = connection.getOutputStream();
            os.write(sb.toString().getBytes());
            os.close();

            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(result);

        } catch (IOException e) {
            e.printStackTrace(System.out);
        }

    }
}

编写验证短信验证码的类VailMobileCode.java

package demo4.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * package_name:demo4.servlet
 * Author:徐亚远
 * Date:2020/2/13 13:33
 * 项目名:code-projects
 * Desription:
 **/
public class VailMobileCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp );
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 得到数据
        String inCode = req.getParameter("mobile_code").toString().toLowerCase();
        String valiCode = req.getSession().getAttribute("valiCode").toString().toLowerCase();
        //2. 验证是否正确
        if(inCode.equals(valiCode)){
            resp.sendRedirect("success.jsp");
        }
        else{
            req.getSession().setAttribute("err", "验证码错误!");
            resp.sendRedirect("mobileCode.jsp");
        }
    }
}

编写前端页面 mobileCode.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2020/2/13
  Time: 13:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>手机短信验证码</title>
</head>

<script type="text/javascript" src="js/jquery.js"></script>
<script language="javascript">
    function get_mobile_code(){
        $.post('phoneCode', {mobile:jQuery.trim($('#mobile').val())}, function(msg) {
//          alert(jQuery.trim(unescape(msg)));
            if(msg.indexOf('提交成功')>=0){
                RemainTime();
                $("#err").text("");
            }else{
//				location.reload();
                $("#err").text("验证码错误!phoneCode");
            }
        });
    };
    var iTime = 59;
    var Account;
    function RemainTime(){
        document.getElementById('zphone').disabled = true;
        var iSecond,sSecond="",sTime="";
        if (iTime >= 0){
            iSecond = parseInt(iTime%60);
            iMinute = parseInt(iTime/60)
            if (iSecond >= 0){
                if(iMinute>0){
                    sSecond = iMinute + "分" + iSecond + "秒";
                }else{
                    sSecond = iSecond + "秒";
                }
            }
            sTime=sSecond;
            if(iTime==0){
                clearTimeout(Account);
                sTime='获取手机验证码';
                iTime = 59;
                document.getElementById('zphone').disabled = false;
            }else{
                Account = setTimeout("RemainTime()",1000);
                iTime=iTime-1;
            }
        }else{
            sTime='没有倒计时';
        }
        document.getElementById('zphone').value = sTime;
    }
</script>
<body>
<form action="vailPhoneCode" method="post" name="formUser" onSubmit="return register();">
    <table width="100%"  border="0" align="left" cellpadding="5" cellspacing="3">
        <tr>
            <td align="right">手机<td>
            <input id="mobile" name="mobile" type="text" size="25" class="inputBg" /><span style="color:#FF0000"> *</span>
        </tr>
        <tr>
            <td align="right">手机验证码</td>
            <td align="left">
                <input type="text" id="mobile_code" name="mobile_code" class="inputBg" size="25" />
                <input id="zphone" type="button" value=" 获取手机验证码 " style="width: 120px"  onClick="get_mobile_code()">
            </td>
        </tr>
        <tr>
            <td> </td>
            <td>
                <input type="submit" value="登录" id="btnOK" />
            </td>
        </tr>
        <tr>
            <td> </td>
            <td>
                <div id="err" style="color: red;">${err }</div>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    
    <!--手机短信验证码servlet-->
    <servlet>
        <servlet-name>mobileCode</servlet-name>
        <servlet-class>demo4.servlet.MobileCode</servlet-class>
    </servlet>
    <!--post提交的url-->
    <servlet-mapping>
        <servlet-name>mobileCode</servlet-name>
        <url-pattern>/phoneCode</url-pattern>
    </servlet-mapping>
   <!--验证手机验证码的servlet-->
    <servlet>
        <servlet-name>vailMobile</servlet-name>
        <servlet-class>demo4.servlet.VailMobileCode</servlet-class>
    </servlet>
    <!--手机短信验证码form表单提交的action路径-->
    <servlet-mapping>
        <servlet-name>vailMobile</servlet-name>
        <url-pattern>/vailPhoneCode</url-pattern>
    </servlet-mapping>
    <!--<welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>-->

</web-app>

效果如图
在这里插入图片描述
如有疑问请联系qq1462638689

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值