秒滴云短信验证登录小demo

短信验证登录demo

<a class="click_login_head" data-href="/member" data-method="offset" data-type="auto">登录</a>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uMjXxj92-1593949318479)(C:\Users\90470\AppData\Roaming\Typora\typora-user-images\1593948052571.png)]

layui.use('layer',function(){
        var $ =layui.jquery,layer = layui.layer;
        //触发事件
        var active={
            offset: function(othis) {
                var type = othis.data('type')
                    , text = othis.text();
                var str='<div class="layer-wrap">' +
                    '<div class="login-box flip-box out flip">' +
                    '<p class="tip-title">手机验证码登录</p>' +
                    '<p class="phone"><i class="icon-phone">' +
                    '</i><span class="ml30">|</span>' +
                    '<input type="phone" name="login_username" placeholder="请输入手机号" required class="phone" maxlength="11" id="phone">' +
                    '</p><p class="code"><i class="icon-password">' +
'</i><span class="ml30">|</span><input class="psw-input" type="password" id="code" name="code" placeholder="请输入动态密码"  maxlength="6">' +
'<input type="button" class="login-get-code get-code fr" id="btn" value="获取动态码"  ></p>' +
                    '<p class="login-reg mt40">新手机号将自动注册</p>' +
                    '<input type="hidden" id="ceshi" value="1">' +
                    '<button class="btn-login" id="lo">登录</button>' +
                    '<a href="javascript:void(0)" class="flip-code">' +
                    '<img src="../../resource/images/code.png" alt=""></a></div></div>';
                layer.open({
                    type: 1, offset: type //具体配置参考:http://www.layui.com/doc/modules/layer.html#offset
                    , id: 'layerDemo' + type //防止重复弹出
                    , title: ''
                    , content: str
                    , scrollbar: false
                    , shade: 0.3 //不显示遮罩
                    , area:['420px','475px']

                });
            }
        };
 $('.head .wrap .click_login_head,.click_register_head').on('click', function(){
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
    }

这里使用了一个layui的弹出窗口,layui的CSS比较好看所以用上了,主要部分是获取动态码和登录那,下面为登录窗口:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7yWayZa5-1593949318483)(C:\Users\90470\AppData\Roaming\Typora\typora-user-images\1593948468302.png)]

下面是JavaScript代码

<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 + "秒后可重新发送");
        }
    }

    var  sms = "";
    //发送验证码
    $(document).on('click','.login-get-code',function(){

        var phone = $("#phone").val();
        if (phone != "") {
            sendMessage();
            $.ajax({
                url : "sendSMS",  //发送请求  目标地址
                type : "post",  //POST方式传输
                datatype:"json",
                data : {  //发送到服务器的数据
                    "phone" : phone
                },
                success : function(result) {
                    console.log(".........................");
                    alert("发送成功");
                    sms = result.data;
                }
            });
        } else {
            alert("请输入手机号");
            return false;
        }
    });
    //点击登录
    $(document).on('click','.btn-login',function(){
        console.log("sms:"+sms);
        var code = $("#code").val();
        if (code == "") {
            alert("请输入验证码");
        } else {
            if (sms == code) {
                window.location.href = "success.jsp";
            } else {
                alert("验证码错误");
            }
            ;
        }
        ;
    });
</script>

从秒滴云官网注册账号认证然后配置相应文件 https://api.miaodiyun.com

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QX2wlCek-1593949318485)(C:\Users\90470\AppData\Roaming\Typora\typora-user-images\1593948998681.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WPhawfgS-1593949318487)(C:\Users\90470\AppData\Roaming\Typora\typora-user-images\1593948757939.png)]

Config文件配置

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

    /*** 开发者注册后系统自动生成的账号,可在官网登录后查看-修改为自己的。*/
    public static final String ACCOUNT_SID = "*fb****54b**44d4****0**2****cbe2";

    /*** 开发者注册后系统自动生成的TOKEN,可在官网登录后查看-修改为自己的。*/
    public static final String AUTH_TOKEN = "****************************f";

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

HttpUtil文件配置

public class HttpUtil
{
    /**
     * 构造通用参数timestamp、sig和respDataType
     *
     * @return
     */
    public static String createCommonParam()
    {
        // 时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date()); //格式化时间

        // 签名   加密的参数值直接进行加密处理:DigestUtils.md5Hex(),括号中放入我们需要加密的参数即可
        String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_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.lineSeparator():(换行符) 剔除了平台无关性,写一次代码跑通在Linux上和Window上都能够运行。
        System.out.println("url:" + System.lineSeparator() + url);
        System.out.println("body:" + System.lineSeparator() + body);

        String result = "";
        try
        {
            OutputStreamWriter out = null;
            BufferedReader in = null; //BufferedReader 是缓冲字符输入流。它继承于Reader。
                                        //BufferedReader 的作用是为其他字符输入流添加一些缓冲功能。
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();// URL 引用的资源的通信链接

            // 设置连接参数
            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; // 读第一行不加换行符 readLine,读取一个文本行,从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
            while ((line = in.readLine()) != null) //readLine,读取一个文本行,从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
            {
                if (firstLine)
                {
                    firstLine = false;
                } else
                {
                    result += System.lineSeparator();
                }
                result += line;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 回调测试工具方法
     *
     * @param url
     * @param reqStr
     * @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;
    }
}

Controller层

@RestController
public class MemberController {

    @PostMapping("/sendSMS")
    public JsonResult getSMS(String phone){
        String code = GetMessageCode.getCode(phone);
        /*String code = "123456";*///测试时使用蚊子再小也是肉!
        System.out.println("code="+code);
        return new JsonResult(0,"验证码发送成功",code);
    }
}

效果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I5R0wA9o-1593949318488)(C:\Users\90470\AppData\Roaming\Typora\typora-user-images\1593949268810.png)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值