发表于: 2019-11-26 22:19:58
1 1134
今天完成的事情:
跑通了昨天的代码,成功收到了短信
把昨天的测试代码转换成工具类
@Component
public class SendMessage {
private static String accessKeyId = "LTAI4FgcQQyguXLJzswYxqTa";
private static String accessKeySecret = "pgIEiGQTMOwjSE9mL2jQyeLatLaEGD";
//替换成自己的accessKeyId和accessKeySecret;
private static String setSignName = "技能树";
private static String setTemplateCode = "SMS_178760211";
//替换成自己的短信签名和模板;
public static String sendMessage(String code, String phone) {
//设置超时时间,可以自行调整;
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient需要的几个参数
final String product = "Dysmsapi";
//短信API产品名称(短信产品名固定,无需修改);
final String domain = "dysmsapi.aliyuncs.com";
//短信API产品域名(接口地址固定,无需修改);
//初始化ascClient,暂时不支持多region(请勿修改)
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
SendSmsRequest request = new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
request.setPhoneNumbers(phone);
//必填:短信签名-可在短信控制台中找到
request.setSignName(setSignName);
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode(setTemplateCode);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
request.setTemplateParam("{\"code\":\"" + code + "\"}");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者;
request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
System.out.println("请求成功!");
}
return product;
}
}
在service层调用工具类
/**
* 发送短信验证码,每1分钟之后可以重复发送,每次有效期为10分钟,每天最多发送5次
* @param phone 手机号
* @return 0:发送成功 1:其他 2:发送过于频繁 3:超过每天最大次数
*/
@Override
public int sendPhone(String phone,String code) {
//默认发送时间为0
long time = 0;
//发送次数,默认为0
int next = 0;
//判断发送时间间隔是否在1分钟之内
if (redisTemplate.opsForValue().get("time"+phone) !=null){
time = (long) redisTemplate.opsForValue().get("time"+phone);
long nowTime =System.currentTimeMillis();
if ((nowTime - time)<1000*60){
return 2;
}
}
//判断24小时之内发送次数是否小于等于最大次数
if (redisTemplate.opsForValue().get("next"+phone) !=null){
next = (int) redisTemplate.opsForValue().get("next"+phone);
logger.info("手机号码发送验证码次数:"+next);
if (next>=5){
return 3;
}
}
String msgStatus = null;
//调用阿里云发送短信验证码
try {
msgStatus = SendMessage.sendMessage(phone,code);
logger.info("阿里云短信发送为:"+msgStatus);
}catch (Exception e){
logger.info("阿里云发送手机信息失败");
e.printStackTrace();
}
//判断发送结果是否成功,将验证码、当前时间以及发送次数放入缓存
if (msgStatus !=null && msgStatus.equals("000000") ){
redisTemplate.opsForValue().set("time"+phone,System.currentTimeMillis(),60);
redisTemplate.opsForValue().set("msgCode"+phone,code,expireTime);
redisTemplate.opsForValue().set("next"+phone,++next,60*60*24);
logger.info("手机号码发送验证码次数:"+redisTemplate.opsForValue().get("next"+phone));
return 0;
}
return 1;
}
/**
* 检验手机验证码是否一致
* @param phone
* @param code
* @return 0:验证成功 1:验证失败
*/
@Override
public int checkPhoneCode(String phone, String code) {
String redisPhoneCode =(String) redisTemplate.opsForValue().get("msgCode"+phone);
logger.info("redis中短信验证码:"+redisPhoneCode);
logger.info("输入的验证码:"+code);
//比对缓存中验证码与用户输入验证码
if (redisPhoneCode != null && code.equals(redisPhoneCode)){
return 0;
}else {
return 1;
}
}
controller
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String insert(User user, HttpServletResponse response,String code) throws UnsupportedEncodingException {
String phone = user.getPhone();
logger.info("新注册用户信息:" + user);
//对传进来的参数进行判空
if (!ObjectUtils.isEmpty(user.getName()) && !ObjectUtils.isEmpty(user.getPwd())) {
if (code == null) {
logger.info("请输入验证码");
return "register";
}
//对比验证码是否一致,0为一致;
else if (userService.checkPhoneCode(phone, code) == 0) {
//注册时,先根据用户名查,如果查不出,说明数据库里没有这条数据则插入,否则返回注册页面
List<User> userName = userService.selectByName(user.getName());
logger.info("用户名为:" + userName);
if (ObjectUtils.isEmpty(userName)) {
//插入时,使用MD5给密码加盐
user.setPwd(Md5Util.MD5(user.getPwd() + user.getId()));
logger.info("加密后的密码:" + user);
user.setPhone(phone);
int regist = userService.insert(user);
String token = DesUtil.encrypt(System.currentTimeMillis() + "|" + user.getName() + "|" + user.getId());
logger.info("token:" + token);
Cookie cookie = new Cookie("token", token);
cookie.setMaxAge(60 * 60);
logger.info("tokenName:" + cookie.getName());
logger.info("tokenValue:" + cookie.getValue());
response.addCookie(cookie);
return "login";
} else {
logger.info("用户名已存在");
return "redirect:/goRegister";
}
}
logger.info("验证码错误");
return "redirect:/goRegister";
}
logger.info("密码不能为空");
return "redirect:/goRegister";
}
修改了注册页面jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8"/>
</head>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function checkPhone()
{
var phone =document.getElementById('phone').value;
console.log("手机号码 = "+phone)
var partten = /^1[3,5,6,7,8]\d{9}$/;
if(partten.test(phone))
{
return true;
}
else
{
alert('请使用手机号码');
}
}
function sendPhone() {
var phone =document.getElementById('phone').value;
console.log("sendPhone: phone = " +phone);
$.ajax({
url: 'phone',
type: 'post',
data: {
'phone':phone,
},
dataType: 'text',
success: function (data) {
alert(data);
console.log("sendCaptcha ==> success: data = " + (data));
},
error: function (data) {
console.log("sendCaptcha ==> error: data = " + (data));
}
});
}
</script>
<html>
<head>
<title>注册</title>
</head>
<body>
<h1>注册</h1>
<form action="/register" name="user" method="post">
用户名:<input type="text" name="name" ><br>
手机号:<input type="text" name="phone" onchange="checkPhone()" id="phone">
<button type="button" onclick="sendPhone()" >获取手机验证码</button><br>
验证码:<input type="text" name="msgCode" value="" placeholder="请输入手机验证码"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="注册">
<a class="a-style" href="/goLogin"> <input type="button" value="已有账号?去登录"></a>
</form>
</body>
</html>
明天计划的事情:完成手机短信接口,添加邮箱邮件接口
遇到的问题:页面点击获取验证码没有反应,日志也没打印出来,好像啥方法都没执行
收获:
学会调用API
评论