Springboot实现短信登录验证

Springboot学习笔记——Java实现短信登录验证功能--Servlet/SSM/SpringBoot都可以用

小白记录一下短信验证登入的实现,方便以后可以拿来直接用。
发短信平台:互亿无线 官网地址

在这里插入图片描述

登入注册啥的就不说了,新人注册会送十条短信验证,想要buy一些学习用的话 也很便宜,就不多说了
在这里插入图片描述
在这里插入图片描述
我们主要需要的就是这个APIID和APPKEY,到时候工具类需要用。

pom工程需要导入两个依赖:

     <!--发送手机验证码-->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

接下来贴上工具类代码:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.IOException;

public class SendSMS {
    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    public static int sendYzCode(String phone) {

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");

        int mobile_code = (int)((Math.random()*9+1)*100000);

        String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");

        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "填你的APIID"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", "填你的APPKEY"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);

        try {
            client.executeMethod(method);

            String SubmitResult =method.getResponseBodyAsString();

            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);

            if("2".equals(code)){
                System.out.println("短信提交成功");
                return mobile_code;
            }

        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
}

工具类只需要把APIID和APPKEY替换一下就可以用啦。

接下来贴前端代码

      <div class="login-style">
                        <dl>
                            <dd><input name="phone" type="text" id="phone" placeholder="您的手机号码"/></dd>
                        </dl>
                        <!--<dl id="yz-code" style="display: none;">
                       <dd><input type="text" id="txtCode2" name="txtCode2" style="width: 133px; margin-right: 10px;" placeholder="验证码" /><img id="Img1" src="" width="90" height="34" title="点击换一个" style="vertical-align: middle; margin-top: -4px;" onclick="this.src='/ImgCode.aspx?t='+Math.random()*100" /></dd>
                       </dl> -->
                        <dl>
                            <dd><input type="text" id="code" name="code" onkeydown="enterHandler(event)" style="width: 133px;"
                                       placeholder="短信验证码"/><input type="button" id="zphone" class="btn_mfyzm"
                                         value="获取手机验证码" /></dd>
                        </dl>
                        <div class="remember">
                            <input type="checkbox" id="issave1" checked/><label for="issave1">下次自动登录</label>
                        </div>
                        <div class="tishi"></div>
                        <button type="button" id="dynamicLogon" style="outline:none">登 录</button>
                    </div>


JS代码:


<script type="text/javascript">
    $(function () {
        $("#zphone").click(function () {
            //先判断是否输入手机号码,再判断手机号格式是否正确,最后判断是否是已经注册过的手机号
            var phone=$("#phone").val();
            if(phone==null||phone==""){
                // $("#msg").text("手机号不能为空").css("color","red");
                Tip('手机号不能为空!');
                $("#phone").focus();
            }else if(!(/^1[3456789]\d{9}$/.test(phone))){
                // $("#msg").text("手机号格式不正确").css("color","red");
                Tip('手机号格式不正确!');
                $("#phone").focus();
            }else{
                $.ajax({
                    url:'user/checkPhone',
                    type:'post',
                    data:{"phone":phone},
                    dataType:'json',
                    success:function (data) {
                        if(data){
                            //发送验证码
                            alert("通过啦!准备执行发送验证码方法");
                            sendCode(phone);
                        }else{
                            Tip('手机号尚未注册,请注册后再登陆!')
                            // $("#msg").html("<a href='login.html'>手机号尚未注册,请注册后再登陆</a>");
                        }
                    }
                });
            }
        })

        //登陆
        $("#dynamicLogon").click(function () {
            var phone=$("#phone").val();
            var code=$("#code").val();
            $.ajax({
                url:'toPhoneLogin',
                type:'post',
                data:{"code":code,"phone":phone},
                dataType:'json',
                success:function (data) {
                    if(data){
                        //登陆成功,网站首页
                        window.location.href="home";
                    }else{
                        //失败
                        Tip('登陆失败,请重试')
                        // $("#msg").text("登陆失败,请重试").css("color","red");
                    }
                }

            })
        });

    })

    function sendCode(phone) {
        $.ajax({
            url:'sendCode',
            type:'post',
            data:{"phone":phone},
            dataType:'json',
            success:function (data) {
                if(data){
                    // $("#msg").text("验证码发送成功").css("color","green");
                    Tip('验证码发送成功!');
                }else{
                    // $("#msg").text("验证码发送失败,请重试").css("color","red");
                    Tip('验证码发送失败,请重试!');
                }
            }

        })
    }
</script>

后台代码:

 /**
     * 发送手机验证码
     */
    @RequestMapping("/sendCode")
    public void sendCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String phone = request.getParameter("phone");
        int code = SendSMS.sendYzCode(phone);

        if (code != 0) {
            session = request.getSession();
            session.setAttribute("yzcode", phone + "#" + code);//1227346764#8765
            response.getWriter().print(true);
        } else {
            response.getWriter().print(false);  //没短信了
        }


    }

    @RequestMapping("/toPhoneLogin")
    public void toPhoneLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        String phone = request.getParameter("phone");
        String code1 = phone + "#" + code;//页面提交的
        String code2 = (String) session.getAttribute("yzcode");//session中获取到的
        if (code1.equals(code2)) {
            //登陆成功,将登陆的用户保存到session中
            //根据用户的电话获取登陆用户
            User loginUser = userService.getUserByPhone(phone);
//            request.getSession()
            session.setAttribute("user", loginUser);
            response.getWriter().print(true);
        } else {
            response.getWriter().print(false);
        }

    }

最后贴上效果图
在这里插入图片描述

在这里插入图片描述
至此短信登录功能就搞定了

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙龙龙呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值