短信验证码
目录
- 短信验证码
- 创建web_user工程 --- 发送队列
- 定义页面属性
- 发送验证码点击
- 添加依赖关系
- 导入配置文件
- web.xml
- spring/applicationContext-jms-producer.xml
- spring/applicationContext-service.xml
- spring/applicationContext-tx.xml
- 在common工程中导入手机号验证工具类PhoneFormatCheckUtils
- 在interface工程中创建UserService
- 在service_user工程中创建UserServiceImp
- 在web_user工程创建控制器UserController
- 创建SMS工程 --- 接收队列
- 添加依赖
- 添加配置文件
- web.xml
- spring/applicationContext-jms-consumer.xml
- spring/applicationContext-service.xml
- 创建发送短信工具类SmsUtil
- 创建监听器, 监听短信消息
- 创建web_user工程 --- 发送队列
短信验证码
创建web_user工程 --- 发送队列
定义页面属性
data:{
userEntity:{
username:'',
password:'',
phone:'',
smscode:''
},
password2:''
},
发送验证码点击
sendCode:function () {
if(this.userEntity.phone==null || this.userEntity.phone==""){
alert("请填写手机号码");
return ;
}
axios.get('/user/sendCode.do',{params:{phone:this.userEntity.phone}}).then(function (response) {
//获取服务端响应的结果
console.log(response.data);
}).catch(function (reason) {
console.log(reason);
});
}
添加依赖关系
com.itxk
dao
1.0-SNAPSHOT
com.itxk
interface
1.0-SNAPSHOT
导入配置文件
web.xml
Archetype Created Web Application
contextConfigLocation
classpath*:spring/applicationContext*.xml
org.springframework.web.context.ContextLoaderListener
spring/applicationContext-jms-producer.xml
<?xml version="1.0" encoding="UTF-8"?>
spring/applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
spring/applicationContext-tx.xml
<?xml version="1.0" encoding="UTF-8"?>
在common工程中导入手机号验证工具类PhoneFormatCheckUtils
public class PhoneFormatCheckUtils {
/**
* 大陆号码或香港号码均可
*/
public static boolean isPhoneLegal(String str)throws PatternSyntaxException {
return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
}
/**
* 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
* 此方法中前三位格式有:
* 13+任意数
* 15+除4的任意数
* 18+除1和4的任意数
* 17+除9的任意数
* 147
*/
public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,4,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
/**
* 香港手机号码8位数,5|6|8|9开头+7位任意数
*/
public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
String regExp = "^(5|6|8|9)\\d{7}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
}
在interface工程中创建UserService
public interface UserService {
public void sendCode(String phone);
}
在service_user工程中创建UserServiceImp
@Service
public class UserServiceImp implements UserService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private ActiveMQQueue smsDestination;
@Override
public void sendCode(final String phone) {
//1. 生成一个随机6为数字, 作为验证码
StringBuffer sb = new StringBuffer();
for (int i =1; i < 7; i++) {
int s = new Random().nextInt(10);
sb.append(s);
}
//2. 手机号作为key, 验证码作为value保存到redis中, 生存时间为10分钟
redisTemplate.boundValueOps(phone).set(sb.toString(), 60 * 10, TimeUnit.SECONDS);
final String smsCode = sb.toString();
//3. 将手机号, 短信内容, 模板编号, 签名封装成map消息发送给消息服务器
jmsTemplate.send(smsDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("mobile", phone);//手机号
message.setString("template_code", "SMS_169111508");//模板编码
message.setString("sign_name", "疯码");//签名
Map map=new HashMap();
map.put("code", smsCode); //验证码
message.setString("param", JSON.toJSONString(map));
return (Message) message;
}
});
}
}
在web_user工程创建控制器UserController
@RequestMapping("/sendCode")
public Result sendCode(String phone) {
try {
if (phone == null || "".equals(phone)) {
return new Result(false, "手机号不能为空!");
}
if (!PhoneFormatCheckUtils.isPhoneLegal(phone)) {
return new Result(false, "手机号格式不正确");
}
userService.sendCode(phone);
return new Result(true, "发送成功!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "发送失败!");
}
}
创建SMS工程 --- 接收队列
添加依赖
junit
junit
4.11
test
com.fmjava
dao
1.0
com.fmjava
interface
1.0
com.aliyun
aliyun-java-sdk-core
4.1.0
添加配置文件
web.xml
Archetype Created Web Application
contextConfigLocation
classpath*:spring/applicationContext*.xml
org.springframework.web.context.ContextLoaderListener
spring/applicationContext-jms-consumer.xml
<?xml version="1.0" encoding="UTF-8"?>
spring/applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
创建发送短信工具类SmsUtil
public class SmsUtil {
/**
* 发送短信
* @param mobile 手机号
* @param template_code 模板号
* @param sign_name 签名
* @param param 验证码
*/
public static void sendSms(String mobile,String template_code,String sign_name,String param) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIFrvvzwdyvzcK", "mjRPox3Y5opiwdV6lCZu6KEBmO0Q0M");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", mobile);
request.putQueryParameter("SignName", sign_name);
request.putQueryParameter("TemplateCode", template_code);
request.putQueryParameter("TemplateParam",param);
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
创建监听器, 监听短信消息
public class SMSListener implements MessageListener {
@Override
public void onMessage(Message message) {
MapMessage map = (MapMessage)message;
try {
SmsUtil.sendSms( map.getString("mobile"),
map.getString("template_code"),
map.getString("sign_name"),
map.getString("param"));
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println(map);
}
}