短信验证功能的实现
一. 准备工作获取发送短信的API等信
1. 首先选取一个运营商
这里以京东万象为例如下图所示:
2. 随机选取一个短信的接口运营商, 这里以106为例
3. 因为正式的使用是需要用钱, 但是有五次测试的机会所以我们注册账号之后, 单击测试
4. 这个页面有两个重要的信息
- APPKEY:3ca172449034b196cd6fd7047e6862de
- Request:
Url:https://way.jd.com/kaixintong/kaixintong?mobile=13205516161&content=【凯信通】您的验证码是:123456&appkey=3ca172449034b196cd6fd7047e6862de - 注意!! 发送的短信中必须含有 【凯信通】 因为是试用还不让人家打广告就过分了
也可以将自己的电话号码输入进去测试一下, 5 次机会还是够用的, 接下来就进入前端的页面
二. 前端代码
- HTML部分
<a href="#" class="vcode-send sms-code-send">获取验证码</a>
<input name="phone" value="" id="phone">
- JavaScript部分
$(function () {
//短信发送
$('.vcode-send').click(function () {
var self = $(this);
var count = 10;
self.addClass('disabled')
self.text(count + '秒后重新获取')
var timer = setInterval(function () {
count--;
if (count > 0) {
self.text(count + '秒后重新获取');
} else {
clearInterval(timer)
self.text('重新获取验证码')
self.removeClass("disabled");
}
}, 1000);
var phone = $("#phone").val();
$.get(domainUrl + "/users/sendVerifyCode", {phone:phone}, function (data) {
console.log(data);
if(data.code == 200){
alert("发送成功")
}else{
alert(data.msg);
}
})
}
});
});
三. bootstrap的启动类中
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
Controller 中的代码实例
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
详解: 博主汪小哥: RestTemplate 使用总结
import org.springframework.web.client.RestTemplate;
@Autowired
private RestTemplate restTemplate;//Springfirework包下的类
@GetMapping("/sendVerifyCode")
public Object sendVerifyCode(String phone){
//1 验证手机号码格式是否正确
AssertUtil.hasLength(phone,"手机号码不能为空");
if(!phone.matches("^1\\d{10}$")){
throw new LogicException("手机号格式不正确!");
}
//2 生成一个随机的验证码, 取前六位
String verifyCode = UUID.randomUUID().toString().replace("-","").substring(0,6);
//String msg="https://way.jd.com/kaixintong/kaixintong?mobile=13205516161&content=【凯信通】您的验证码是:123456&appkey=4128e07e384d610092ea10fec46f1f90";
String url="商家请求的URL?mobile={1}&content={2}&appkey={3}";
String msgContext="【凯信通】您的验证码是:"+verifyCode;
String appKey="xxxxxxxxxxxxxx"; //先前获取到的appKey
//3 把验证码发送短信至指定手机
Map map = restTemplate.getForObject(url, Map.class, phone, msgContext, appKey);
Object result = map.get("result");//发短信返回的结果
if(result.toString().indexOf("Success")==-1){
throw new LogicException("短信发送失败");
}
//可以同时在控制台输出一下看看是否与发送到手机上的验证码一致
System.out.println("result:"+result);
System.out.println(msgContext);
//4 验证码信息保存下来
//cookie,session,redis,mongodb
/*
cookie 数据存在浏览器端,有时间限制
session 数据存在服务器,有时间限制,只能存在一个服务器中
redis 数据存在内存中,有时间限制 胜出
mongodb 存在数据库中,没有时间限制
*/
redisService.setValidateCode(phone,verifyCode);
return JsonResult.success();
}
- JsonResult 是回复的工具类
package cn.xxxx.util;
import ...;
/**
*
* jsonResult
*
* {
* code:
* msg:
* data:[]
* }
*/
@Setter
@Getter
@NoArgsConstructor
public class JsonResult<T> {
public static final int CODE_SUCCESS = 200;
public static final String MSG_SUCCESS = "操作成功";
public static final int CODE_NOLOGIN = 401;
public static final String MSG_NOLOGIN = "请先登录";
public static final int CODE_ERROR = 500;
public static final String MSG_ERROR = "系统异常,请联系管理员";
public static final int CODE_ERROR_PARAM = 501; //参数异常
private int code; //区分不同结果, 而不再是true或者false
private String msg;
private T data; //除了操作结果之后, 还行携带数据返回
public JsonResult(int code, String msg, T data){
this.code = code;
this.msg = msg;
this.data = data;
}
public static <T> JsonResult success(T data){
return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, data);
}
public static JsonResult success(){
return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, null);
}
public static <T> JsonResult error(int code, String msg, T data){
return new JsonResult(code, msg, data);
}
public static JsonResult defaultError(){
return new JsonResult(CODE_ERROR, MSG_ERROR, null);
}
public static JsonResult noLogin() {
return new JsonResult(CODE_NOLOGIN, MSG_NOLOGIN, null);
}
}