java实现短信验证码登陆 demo

这篇博客详细介绍了如何使用Java、Servlet和JSP来实现手机短信验证码发送功能。首先选择秒嘀云平台并完成认证获取参数,然后创建短信模板,接着编写Java代码实现发送短信接口,并提供了一个HTTP请求工具类。最后展示了项目目录结构,包括Config.java配置类、HttpUtil.java工具类和GetMessageCode.java验证码获取类,以及LoginServlet和login.jsp页面代码。

java + servlet+ jsp实现发送手机短信验证码

【1】选择平台,完成认证。

短信登陆平台很多,自己可以看个人爱好选择。

我们使用的API平台是:秒嘀云: https://sms.miaodiyun.com/login.html

注册该平台,完成认证就可以获取到参数:ACCOUNT SID ,  AUTH TOKEN , API

1422859-20190705142653064-1609609498.jpg

【2】创建短信模板 (该模板必须创建,通过平台审核只会才可以使用,而且后续的参数 smsContent 要和模板中的一致 )

1422859-20190705143225975-976786085.jpg

【3】发送短信接口

http://www.miaodiyun.com/doc/https_sms.html

编写java手机短信发送代码

【4】项目目录结构  (idea 中创建的普通web工程)

1422859-20190705144007850-1171527959.jpg

【5】Config.java

public class Config {
    /**
     * url前半部分
     */
    public static final String BASE_URL = " https://openapi.miaodiyun.com/distr*******dSMS";

    /**
     * 开发者注册后系统自动生成的账号,可在官网登录后查看
     */
    public static final String ACCOUNT_SID = "fcf340ac***********915927";

    /**
     * 开发者注册后系统自动生成的TOKEN,可在官网登录后查看
     */
    public static final String AUTH_TOKEN = "648384a1***********2c33e4f";

    /**
     * 响应数据类型, JSON或XML
     */
    public static final String RESP_DATA_TYPE = "JSON";
}

【6】http请求工具HttpUtil.java

package com.miaodi.comment;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * http请求工具
 */
public class HttpUtil {
    /**
     * 构造通用参数timestamp、sig和respDataType
     * 
     * @return
     */
    public static String createCommonParam(String sid,String token) {
        // 时间戳
        long timestamp = System.currentTimeMillis();
        // 签名
        String sig = DigestUtils.md5Hex(sid + token + timestamp);
        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
    }

    /**
     * post请求
     * 
     * @param url
     *            功能和操作
     * @param body
     *            要post的数据
     * @return
     * @throws IOException
     */
    public static String post(String url, String body) {
        System.out.println("body:" + System.lineSeparator() + body);

        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 回调测试工具方法
     * 
     * @param url
     * @return
     */
    public static String postHuiDiao(String url, String body) {
        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);

            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

【7】获取验证码类 GetMessageCode.java

package com.miaodi.getcode;

import com.alibaba.fastjson.JSONObject;
import com.miaodi.comment.Config;
import com.miaodi.comment.HttpUtil;

import java.net.URLEncoder;


public class GetMessageCode {

    private static String accountSid = Config.ACCOUNT_SID;
    private static String rod=smsCode();   //生成一个随机验证码
    private static String smsContent = "【南京车纷享汽车服务有限公司】登录验证码:"+rod +",如非本人操作,请忽略此短信";

    //创建验证码
    public static String smsCode(){
        String random=(int)((Math.random()*9+1)*100000)+"";
        return random;
    }

    //根据相应的手机号发送验证码
    public static String getCode(String phone){
        String tmpSmsContent = null;
        try{
            tmpSmsContent = URLEncoder.encode(smsContent, "UTF-8");
        }catch(Exception e){
            e.getMessage();
        }

        String url = Config.BASE_URL;
        String body = "accountSid=" + accountSid + "&to=" + phone + "&smsContent=" + tmpSmsContent
                + HttpUtil.createCommonParam(Config.ACCOUNT_SID,Config.AUTH_TOKEN);

        // 提交请求
        String result = HttpUtil.post(url, body);


        //字符串转json对象
        JSONObject jsonObject = JSONObject.parseObject(result);
        String respCode = jsonObject.getString("respCode");

        System.out.println("验证码:"+rod);
        System.out.println("结果码:"+respCode);

        //反馈-00000状态码标识请求成功,
        String defaultRespCode="0000";
        if(defaultRespCode.equals(respCode)){
            return rod;
        }else{
            return defaultRespCode;
        }
    }

}

【8】servlet类 LoginServlet.java

package com.tencent.loginservlet;

import com.miaodi.getcode.GetMessageCode;

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(name = "LoginServlet",urlPatterns = "/sendSMS")
public class LoginServlet extends HttpServlet {

    /** serialVersionUID*/
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String  phone=request.getParameter("phone");
        //根据获取到的手机号发送验证码
        String code = GetMessageCode.getCode(phone);
        System.out.println("返回code"+code);
        response.getWriter().print(code);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

}

【9】login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <base href="<%=basePath%>">
    <title>测试短信登陆</title>
</head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">

<link rel="stylesheet" href="CSS/bootstrap/bootstrap.min.css" />
<script type="text/javascript" src="js/jQuery/jquery-3.4.1.js"></script>
<style type="text/css">
    #login {
        width: 450px;
        height: 100px;
        margin: 126px auto;
    }

    #btn {
        margin-left: 100px;
        margin-top: -25px;
        width: 120px;
        height: 25px;
        font-size: 11px;
    }

    body {
        background-color: #ecfcf9;
    }
</style>
</head>
<script type="text/javascript">
    var InterValObj; //timer变量,控制时间
    var count = 60; //间隔函数,1秒执行
    var curCount;//当前剩余秒数

    function sendMessage() {
        curCount = count;
        $("#btn").attr("disabled", "true");
        $("#btn").val(curCount + "秒后可重新发送");
        InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次请求后台发送验证码 TODO
    }
    //timer处理函数
    function SetRemainTime() {
        if (curCount == 0) {
            window.clearInterval(InterValObj);//停止计时器
            $("#btn").removeAttr("disabled");//启用按钮
            $("#btn").val("重新发送验证码");
        } else {
            curCount--;
            $("#btn").val(curCount + "秒后可重新发送");
        }
    }
</script>

<body>
<div class="container">
    <div id="login">
        <fieldset>
            <div id="legend" class="">
                <legend class="">用户登录</legend>
            </div>
            <form class="form-horizontal" role="form">

                <div class="form-group"> <label class="col-sm-2 control-label">手机号</label>
                    <div class="col-sm-5">
                        <input type="text" class="form-control" id="phone" name="phone" placeholder="请输入您的手机号" required>
                    </div>
                </div>

                <div class="form-group"> <label class="col-sm-2 control-label">验证码</label>
                    <div class="col-sm-3">
                        <input type="code" class="form-control" id="code" name="code" placeholder="验证码" required>
                        <input class="btn btn-default" id="btn" name="btn" value="发送验证码" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="button" class="btn btn-success" id="lo">手机号登录</button>
                    </div>
                </div>

            </form>
        </fieldset>
    </div>
</div>
</body>

<script type="text/javascript">
    var sms = "";
    $("#btn").click(function() {
        var phone = $("#phone").val();
        if (phone != "") {
            sendMessage();
            $.ajax({
                url : "sendSMS",  //发送请求
                type : "post",
                data : {
                    "phone" : phone
                },
                success : function(result) {
                    sms = result;
                }
            });
        } else {
            alert("请输入手机号");
            return false;
        }
    });
    $("#lo").click(function() {
        var code = $("#code").val();
        if (code == "") {
            alert("请输入验证码");
        } else {
            if (sms == code) {
                window.location.href = "success.jsp";
            } else {
                alert("验证码错误");
            }
            ;
        }
        ;
    });
</script>

</html>

【10】备注:

lib是一些jar包,jar可以从秒嘀云平台的demo中导入到自己的工程中,也可以自己从网上下载,主要用到的是commons-codec-1.9.jar  做加密用的,fastjson-1.2.49.jar 是作json转化用的,其他的没啥用。

页面中引入的bootstrap 和jQuery 库 自己可以从网上下载。succee.jsp 等可以自定义。

转载于:https://my.oschina.net/u/3459265/blog/3089761

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值