Java笔记-手机验证码实现

这里以 互亿无线 的为例。

逻辑上为,自己的java服务器生成随机数,然后发给那个 手机短信厂家,厂家把这个随机数发给用户手机。用户提交这个验证码后,再对比。

这里互亿无线,的接口有点坑,用http,而且直接明文传输。不过还好的是,可以绑定服务器IP地址。这样也还算安全

程序运行截图如下:

输入手机号,点击获取手机验证码,获取后,点击登录,服务器那边判断,即可。

程序结构如下:

源码如下:

LoginServlet.java

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

@WebServlet(value = "/loginDemo")
public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        //1. 得到数据
        String inCode = request.getParameter("mobile_code").toString().toLowerCase();
        String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
        //2. 验证是否正确
        if(inCode.equals(valiCode)){

            response.sendRedirect("success.jsp");
        }
        else{
            String url = request.getHeader("Referer");
            response.sendRedirect(url);
        }
    }

}

SMSServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;


@WebServlet(value = "/sms")
public class SMSServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            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); //获取随机数
        request.getSession().setAttribute("valiCode", mobile_code);

        String account = "xxxxxxxxxx"; //查看用户名是登录用户中心->验证码短信->产品总览->APIID
        String password = "xxxxxxxxxxxxxxxxxxxxxxx";  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
        String mobile = request.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();
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(result);

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

    }
}

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!doctype html>
<html>
<head>
    <title>demo</title>
</head>
<script type="text/javascript"src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
    function get_mobile_code(){
        $.post('sms', {mobile:jQuery.trim($('#mobile').val())}, function(msg) {
            if(msg.indexOf('提交成功')>=0){
                RemainTime();
            }else{
                $("#err").text("验证码错误!");
            }
        });
    };
    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="loginDemo" method="post" name="formUser">
    <label>手机</label>
    <input id="mobile" name="mobile" type="text" size="25" /><br/>
    <label>手机验证码</label>
    <input type="text" id="mobile_code" name="mobile_code" /><br/>
    <input id="zphone" type="button" value=" 获取手机验证码 " onClick="get_mobile_code()" /><br/>
    <input type="submit" value="登录" id="btnOK" />
</form>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: cff
  Date: 2020/2/2
  Time: 11:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>SUCCESS</h1>
</body>
</html>
发布了1269 篇原创文章 · 获赞 1970 · 访问量 179万+

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/104144812