当前位置: 首页 > news >正文

java手机短信验证,并存入redis中,验证码时效5分钟

目录

1、注册发送短信账号一个账号

2、打开虚拟机,将redis服务端打开

3、创建springboot工程,导入相关依赖

4、写yml配置

5、创建controller层,并创建controller类

6、创建service层,并创建service类

7、创建工具类,将发送短信的代码放入工具类

8、返回值工具类

9、写前端代码验证


结合第三方API和redis实现以下功能:

1:手机短信验证,每条验证码有效期为5分钟,

2:五分钟内如果该手机号再次获取验证码,则提示短信已发送,请XX分钟后(剩余过期时间)重新

获取

3:每个手机号每天最多只能发送3次,24小时后可发送次数重置

1、注册发送短信账号一个账号

网址:https://www.ihuyi.com/

注册送10条免费短信

 发送短信需要对接相关资源

2、打开虚拟机,将redis服务端打开

3、创建springboot工程,导入相关依赖

工程结构

 

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>io.projectreactor</groupId><artifactId>reactor-test</artifactId><scope>test</scope></dependency>

4、写yml配置

spring:redis:port: 6379  #端口号host: 192.168.138.129 #虚拟机IP地址password: 123456 #密码database: 0 #redis默认数据库timeout: 5000mvc:static-path-pattern: /**   #加载静态资源thymeleaf:cache: false  #关闭页面缓存mode: HTML    #模板模式suffix: .html #构建URL时附加到查看名称的后缀

5、创建controller层,并创建controller类

@Controller
public class CodeController {@Autowiredprivate CodeService codeService;//访问8080直接进入index页面@GetMapping("/")public String index(){return "index";}/*** @description 获取验证码* @author * @date 2023-02-13 15:25:02* @param phone* @return {@link String}*/@PostMapping("/getPhone")@ResponseBodypublic String phone(String phone){//调用方法,发送手机验证码String result = codeService.getCode(phone);if (result != null){return result;}return JSON.toJSONString(new R("0","验证码发送失败,请重试!",null));}/*** @description 登录验证* @author * @date 2023-02-13 15:25:18* @param phone* @param code* @return {@link String}*/@GetMapping("/login.do")public String login(String phone,String code){boolean flag = codeService.checkCode(phone, code);// 判断是否相同if (flag){// 相同,通过,跳转页面return "login";}else {// 不同,不通过,返回原页面return "index";}}
}

6、创建service层,并创建service类

@Service
public class CodeService {/*** @description 获取验证码* @author * @date 2023-02-13 14:10:27* @param* @return {@link String}*/public String phoneCode(){return (int)((Math.random()*9+1)*100000)+"";}/*** @description 根据手机号获取验证码,并设置有效期* @author * @date 2023-02-13 14:11:42* @param* @return {@link String}*/public String getCode(String phone){//手机号对应的次数keyString countKey = phone +"_count";//手机验证码的keyString codeKey = phone + "_code";//获取手机号次数String phoneCount = RedisTools.get(countKey);if (phoneCount == null || "".equals(phoneCount)){//第一次获取验证码,存入redisRedisTools.setEx(countKey,"1",1, TimeUnit.DAYS);}else if (Integer.parseInt(phoneCount) <= 2){//获取验证码剩余时间Long timeRemaining = RedisTools.getExpire(codeKey);if (timeRemaining > 0){//转换为分钟long m = timeRemaining / 60;//转换为秒long s = timeRemaining % 60;return JSON.toJSONString(new R("0","短信已成功发送,请"+m+"分钟"+s+"秒后重新获取",null));}//获取验证码次数加一RedisTools.incrBy(countKey,1);}else {return JSON.toJSONString(new R("0","今日发送验证码的次数已达上限!",null));}//获取验证码String phoneCode = this.phoneCode();//发送验证码,获取返回结果String result = CodeTools.getCode(phone, code);//String result = "{\"code\":2,\"msg\":\"account或password不正确\",\"smsid\":\"0\"}";//如果结果为空则发送验证码失败if (result == null){return JSON.toJSONString(new R("0","验证码获取失败!",null));}else {//将验证码存入redisRedisTools.setEx(codeKey,phoneCode,5,TimeUnit.MINUTES);}// 将字符串类型的json数据转换为json对象JSONObject jsonObject = JSONObject.parseObject(result);// 从json对象中拿取code   code为2时返回为正常String code = jsonObject.get("code").toString();if (code.equals("2")){return JSON.toJSONString(new R("1","验证码已发送,请注意查看!",null));}else {return JSON.toJSONString(new R("0","验证码发送失败,请重试!",null));}}/*** @description 登录验证* @author * @date 2023-02-13 14:38:15* @param phone* @param code* @return {@link boolean}*/public boolean checkCode(String phone,String code){String phoneCode ="";try {phoneCode = RedisTools.get(phone + "_code");}catch (Exception e){e.printStackTrace();}//判断验证码是否正确boolean flag = phoneCode.equals(code);return flag;}
}

7、创建工具类,将发送短信的代码放入工具类

发送短信工具类

String account = ""--->查看用户名是登录用户中心->验证码短信->产品总览->APIID

String passwor = ""----> //查看密码请登录用户中心->验证码短信->产品总览->APIKEY

public class CodeTools {/*** @description 发送验证码* @author * @date 2023-02-13 16:04:08* @param phone* @param mobile_code* @return {@link String}*/public static String getCode(String phone,String mobile_code){String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";//int mobile_code = (int)((Math.random()*9+1)*100000); //获取随机数//查看用户名是登录用户中心->验证码短信->产品总览->APIIDString account = "";//查看密码请登录用户中心->验证码短信->产品总览->APIKEYString password = "";// 设置短信内容String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");String line, result = "";try {// 创建URL对象URL url = new URL(postUrl);// 创建连接对象HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 同意输出//允许连接提交信息connection.setDoOutput(true);//网页提交方式“GET”、“POST”connection.setRequestMethod("POST");// 设置字符编码connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("Connection", "Keep-Alive");StringBuffer sb = new StringBuffer();sb.append("account="+account);sb.append("&password="+password);sb.append("&mobile="+phone);sb.append("&content="+content);// 设置返回数据的数据格式为JSONsb.append("&format=json");// 以各种流的转换请求数据java.io.OutputStream os =  connection.getOutputStream();os.write(sb.toString().getBytes());os.close();// 读取请求数据的结果BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));while ((line = in.readLine()) != null) {// 对数据进行拼接result += line + "\n";}in.close();System.out.println(result);} catch (IOException e) {e.printStackTrace(System.out);return null;}// 返回API的返回结果,为JSON,,,,有的可能为XML,,注意自己的设置return JSON.toJSONString(new R("1","验证码已发送,请注意查看!",null));}
}

8、返回值工具类

@Data
public class R<T>{private String code;private String msg;private T data;public R() {}public R(String code, String msg, T data) {this.code = code;this.msg = msg;this.data = data;}@Overridepublic String toString() {return "R{" +"code='" + code + '\'' +", msg='" + msg + '\'' +", data=" + data +'}';}
}

deris工具类提连接

链接:https://pan.baidu.com/s/1CCDD496oIGdRfqAIx8OQ2Q?pwd=tewx 
提取码:tewx

9、写前端代码验证

登录页面代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="/js/jquery-1.12.4.js"></script><script src="/js/phone.js"></script>
</head>
<body><form action="login.do" method="get">电话:<input type="text" id="phone" name="phone"><span id="sub">获取验证码</span><span id="msg"></span><br>获取验证码:<input type="text" id="code" name="code"><input type="submit" value="登录"></form></body>
</html>

js代码

$(function (){$("#sub").click(function () {let phone = $("#phone").val();$.ajax({"url": "getPhone","type": "post","data": "phone=" + phone,"dataType": "json","success": function (result) {//调用方法var code = result.codevar msg = result.msgif (code==="0"){$("#msg").html(msg);}else if (code==="1"){$("#msg").html(msg);}},"error": function () {alert("校验失败00!")}});})
})
http://www.lryc.cn/news/5178.html

相关文章:

  • kubectl命令控制远程k8s集群(Windows系统、Ubuntu系统、Centos系统)
  • 【求解器-COPT】COPT的版本更新中,老版本不能覆盖的问题
  • Vue3.0文档整理:一、简介
  • vue2 diff算法及虚拟DOM
  • Ray和极客们的创新之作,2月18日来发现
  • Dubbo 源码分析 – 集群容错之 Router
  • 行人检测(人体检测)3:Android实现人体检测(含源码,可实时人体检测)
  • 【图像分类】基于PyTorch搭建LSTM实现MNIST手写数字体识别(单向LSTM,附完整代码和数据集)
  • Kotlin 1.8.0 现已发布,有那些新特性?
  • likeshop单商户SaaS商城系统—无限多开,搭建多个商城
  • Bean(Spring)的执行流程和生命周期
  • 工作记录------PostMan自测文件导入、导出功能
  • 上海亚商投顾:沪指震荡上行 大消费板块全线走强
  • linux中的图形化UDP调试工具
  • 前端react面试题指南
  • 深入浅出原核基因表达调控(乳糖操纵子、色氨酸操纵子)
  • 10分钟理解Mysql索引
  • nVisual综合布线可视化管理系统解决方案
  • 34岁测试工程师被辞退,难道测试岗位真的只是青春饭吗?
  • Java中常见的空指针异常
  • d亚当替换工厂模式
  • Real-time Scene Text Detection with Differentiable Binarization
  • 国外客户只想跟工厂合作?可以这样破解
  • c++重中之重:“换个龟壳继续套娃“:运算符重载等的学习
  • RabbitMQ简单使用
  • Lambda表达式
  • JSON数据格式【学习记录】
  • LeetCode——1234. 替换子串得到平衡字符串
  • Web自动化测试——selenium篇(二)
  • RK3399平台开发系列讲解(文件系统篇)虚拟文件系统的数据结构