完成一个手机验证码功能:
思路:
因为课程主要讲的后端,所以前端页面就不写了,我们只写后端的逻辑代码。
先完成第一个部分,生成6位数字验证码:
测试有无生成六位随机验证码;
第二个方法:每个手机每天只能发送三次,验证码放到redis中,设置过期时间。
//2、每个手机每天只能发送三次,验证码放到redis中,设置过期时间120s。
public static void verifyCode(String phone){
//连接redis
Jedis jedis = new Jedis("192.168.188.100",6379);
//拼接key
//手机发送次数key
String countKey = "VerifyCode"+phone+":count";
//验证码key
String codeKey = "VerifyCode"+phone+":code";
//每个手机没有只能发送三次
String count = jedis.get(countKey);
if(count == null) {
//没有发送次数,第一次发送
//设置发送次数为1
jedis.setex(countKey,20*60*60,"1");
}else if(Integer.parseInt(count) <= 2){
//发送次数+1
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
//发送三次,不能再发送
System.out.println("今日发送已达三次!");
jedis.close();
}
//发送验证码放到redis里面去
String vcode = getCode();
jedis.setex(codeKey,120,vcode);
jedis.close();
}
第三个方法:验证码校验
测试:
先运行,发送一次先;然后我们去redis中查看消息:
可以看见有两个键了,我们查看其中一个验证码:
可以看见访问次数以及验证码都查出来了。