手机验证码_redis模拟实现

3 篇文章 0 订阅
2 篇文章 0 订阅

手机验证码案例

1.SSM阶段已结束,随着课程的深入,4天的redis以及Linux学习,让我们对redis有了一定的理解,比如redis这种非关系型数据库,缓解了mysql高并发问题,数据类型更加丰富,对于redis,我们仅需要通过虚拟机装个Linux系统,然后在里面装个redis,然后装个客户端即可.,最后Java与之连接,可谓妙哉~
2.核心代码展示

//处理发送验证码的Servlet
@WebServlet("/SendCodeServlet")
public class SendCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户填写的验证码
        String phoneNo = request.getParameter("phone_no");
        System.out.println("phoneNo = " + phoneNo);

        //查询此手机号发送验证码的次数
        Jedis jedis = new Jedis("192.168.6.132", 6379);
        String countKey = phoneNo + ":count";
        String count = jedis.get(countKey);
        if(count == null){
            //第一次发送,初始化发送次数 1,有效期为当日剩余时间
            jedis.setex(countKey, (int)getTheLeftSeconds(), "1");
        }else if(count.equals("3")){
            //已发送3次,达到上限,不再发送,响应"limit"
            response.getWriter().print("limit");
            //释放资源
            jedis.close();
            return;
        }else{
            //已发送,但未达到3次,发送次数 +1
            jedis.incr(countKey);
        }

        //生成6位验证码
        String code = getCode(6);
        System.out.println("code = " + code);

        //存入Redis中,有限期2分钟
        jedis.setex(phoneNo+":login", 120, code);
        //发送验证码到用户的手机上(省略....)

        //发送短信成功,响应true
        response.getWriter().print(true);
        //释放资源
        jedis.close();
    }

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

    // 随机生成验证码的方法
    private String getCode(int len) {
        String code = "";
        for (int i = 0; i < len; i++) {
            int rand = new Random().nextInt(10);
            code += rand;
        }
        return code;
    }

    //获取当天剩余秒数的方法
    private long getTheLeftSeconds() {
        //获取现在的时间
        LocalTime now = LocalTime.now();
        //获取当日23点59分59秒的时间
        LocalTime end = LocalTime.of(23, 59, 59);
        //获取end与now相差的秒数
        long millis = Duration.between(now, end).toMillis() / 1000;
        return millis;
    }
}
//处理验证验证码请求的Servlet
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户填写的手机号、验证码
        String phoneNo = request.getParameter("phone_no");
        String verifyCode = request.getParameter("verify_code");

        //到Redis中根据Key查找
        Jedis jedis = new Jedis("192.168.6.132", 6379);
        String loginKey = phoneNo + ":login";
        String loginCode = jedis.get(loginKey);
        //Redis中存储的验证码 与 用户填写的验证码一致
        if(loginCode != null && loginCode.equals(verifyCode)){
            //校验成功,删除Redis中的验证码
            jedis.del(loginKey);
            //响应"true"
            response.getWriter().print(true);
            //释放资源
            jedis.close();
        }
    }

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

前端页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
        <script src="static/jquery/jquery-3.1.0.js"></script>
<%--        关联CSS样式--%>
        <link href="static/bs/css/bootstrap.min.css" rel="stylesheet"/>
        <script src="static/bs/js/bootstrap.min.js"></script>

    </head>
    <body>
        <div class="container">
            <div class="row">
                <div id="alertdiv" class="col-md-12">
                    <form class="navbar-form navbar-left" role="search" id="codeform">
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="填写手机号" name="phone_no">
                            <button type="button" class="btn btn-default" id="sendCode">发送验证码</button>
                            <br>
                            <font id="countdown" color="red"></font>
                            <br>
                            <input type="text" class="form-control" placeholder="填写验证码" name="verify_code">
                            <button type="button" class="btn btn-default" id="verifyCode">确定</button>
                            <font id="result" color="green"></font><font id="error" color="red"></font>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </body>
    <script type="text/javascript">
        var t = 120;//设定倒计时的时间
        var interval;

        function refer() {
            $("#countdown").text("请于" + t + "秒内填写验证码 "); // 显示倒计时
            t--; // 计数器递减
            if (t <= 0) {
                clearInterval(interval);
                $("#countdown").text("验证码已失效,请重新发送! ");
            }
        }

        $(function () {
            $("#sendCode").click(function () {

                $.post("SendCodeServlet", $("#codeform").serialize(), function (data) {
                    if (data == "true") {
                        t = 120;
                        clearInterval(interval);
                        interval = setInterval("refer()", 1000);//启动1秒定时
                    } else if (data == "limit") {
                        clearInterval(interval);
                        $("#countdown").text("单日发送超过次数! ")
                    }
                });
            });

            $("#verifyCode").click(function () {

                $.post("CheckCodeServlet", $("#codeform").serialize(), function (data) {
                    if (data == "true") {
                        $("#result").attr("color", "green");
                        $("#result").text("验证成功");
                        clearInterval(interval);
                        $("#countdown").text("")
                    } else {
                        $("#result").attr("color", "red");
                        $("#result").text("验证失败");
                    }
                });
            });


        });
    </script>
</html>

3.tomcat部署发布后测试截图
在这里插入图片描述在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿松のblog

下一个构架师就是你~

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

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

打赏作者

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

抵扣说明:

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

余额充值