目录
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: 5000
mvc:
static-path-pattern: /** #加载静态资源
thymeleaf:
cache: false #关闭页面缓存
mode: HTML #模板模式
suffix: .html #构建URL时附加到查看名称的后缀
5、创建controller层,并创建controller类
@Controller
public class CodeController {
@Autowired
private 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")
@ResponseBody
public 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){
//手机号对应的次数key
String countKey = phone +"_count";
//手机验证码的key
String codeKey = phone + "_code";
//获取手机号次数
String phoneCount = RedisTools.get(countKey);
if (phoneCount == null || "".equals(phoneCount)){
//第一次获取验证码,存入redis
RedisTools.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 {
//将验证码存入redis
RedisTools.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); //获取随机数
//查看用户名是登录用户中心->验证码短信->产品总览->APIID
String account = "";
//查看密码请登录用户中心->验证码短信->产品总览->APIKEY
String 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);
// 设置返回数据的数据格式为JSON
sb.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;
}
@Override
public 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.code
var msg = result.msg
if (code==="0"){
$("#msg").html(msg);
}else if (code==="1"){
$("#msg").html(msg);
}
},
"error": function () {
alert("校验失败00!")
}
});
})
})