发表于: 2020-09-19 21:55:11
0 1430
今天完成的事情:
完成短信 ,邮件发送
昨天没成功是因为容联云需要实名认证
短信jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>手机注册</title>
<body>
<strong><p>手机号注册</p></strong>
<div "color:#6a8759;">"contain" >
<form action="/RegisterByPhone" method=POST >
请输入用户名:<br>
<input type="text" name="username" id="username" placeholder="请输入小于16位的用户名" maxlength="16">
${NameError}
<br>
请输入密码:<br>
<input type="text" name="password" id="pass" placeholder="请输入小于16位的密码" maxlength="16">
${PassError}
<br>
请再次确认密码:<br>
<input type="text" name="againPassword" id="againPass" placeholder="请再次输入密码" maxlength="16" >
${TwoPassError}
<br>
手机号:<br>
<input type="text" name="phone" id="phone2" placeholder="请输入11位手机号" maxlength="11">
${PhoneError}
<br>
请输入收到的验证码:<br>
<input type="text" name="yzm" id="yzm" placeholder="请输入4位验证码" maxlength="4">
<input type="button" name="" id="verCodeBtn" value="获取验证码" onclick="settime(this);"/>
${YzmError}
<br>
<br>
<input type="submit" value="注册">
</form>
</div>
<br>
<script src="http://www.lanrenzhijia.com/ajaxjs/jquery.min.js"></script>
<script>
//验证码
var counts = 120;
function settime(val) {
if(counts == 0) {
val.removeAttribute("disabled");
val.value = "获取验证码";
counts = 120;
return false;
} else {
val.setAttribute("disabled", true);
val.value = "重新发送(" + counts + ")";
counts--;
}
setTimeout(function() {
settime(val);
}, 1000);
}
//获取验证码
$(function(){
$("#verCodeBtn").click(function() {
var userinfo = {
"UserPhoneNum": $("input[name='phone']").val()
}
$.ajax({
url: "/sendPhoneYzm",
data: userinfo,
type: "post",
});
});
})
</script>
</hr>
<a href="/RegisterByEmailPage">如果你想使用邮箱注册,请点击此处</a>
<br>
<a href="/login">已有账号?点此直接登录</a>
</body>
</html>
发送短信工具类
spring管理账号密码
properties文件
serverIp =app.cloopen.com
serverPort =8883
accountSId =8aaf07087249953401726b199a7a110a
accountToken =241c0dcb24e04fc48ded38486f33fa81
appId =8aaf07087249953401726b199b451110
bean(set方法注入)
<!-- 用Spring管理短信接口的bean对象-->
<bean id="sendMessage" class="com.mb.util.SendMessageUtil">
<property name="serverIp" value="${serverIp}"></property>
<property name="serverPort" value="${serverPort}"></property>
<property name="accountSId" value="${accountSId}"></property>
<property name="accountToken" value="${accountToken}"></property>
<property name="appId" value="${appId}"></property>
</bean>
发短信工具类
package com.mb.util;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import lombok.Data;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.print.DocFlavor;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class SendMessageUtil {
@Autowired
RedisTemplate redisTemplate;
private static Logger logger = Logger.getLogger(SendMessageUtil.class);
private String serverIp;
private String serverPort;
private String accountSId;
private String accountToken;
private String appId;
//set方法注入
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public void setAccountSId(String accountSId) {
this.accountSId = accountSId;
}
public void setAccountToken(String accountToken) {
this.accountToken = accountToken;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void sendTelCode(String tel) {
logger.info("输入的手机号是"+tel);
logger.info("准备放入SDK的参数为========="+serverIp+serverPort+accountSId+accountToken+appId);
CCPRestSmsSDK sdk = new CCPRestSmsSDK();
// 初始化服务器地址和端口,格式如下,服务器地址不需要写https:
sdk.init(serverIp, serverPort);
// 初始化主帐号和主帐号TOKEN
sdk.setAccount(accountSId, accountToken);
// 初始化应用ID
sdk.setAppId(appId);
logger.info("生成的SDK为==========="+sdk);
// 1-电话作为参数输入
// 2-模板ID
String templateId = "1";
logger.info("模板Id是:" + templateId);
// 3-随机四位验证码
int yzm = (int) ((Math.random() * 8999) + 1000);
//验证码转化为Strig类型
String pyzm = String.valueOf(yzm);
logger.info("验证码是:" + pyzm);
String redisResult = (String)redisTemplate.opsForValue().get(tel);
logger.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+redisResult);
if(redisResult == null) {
// 将手机号为key,验证码为value,存储缓存,设置过期时间2分钟
try {
redisTemplate.opsForValue().set(tel, pyzm, 120, TimeUnit.SECONDS);
logger.info("手机号,验证码放入缓存成功");
} catch (Exception e) {
logger.info("手机号,验证码放入缓存失败");
}
}else {
try {
redisTemplate.delete(tel);
logger.info("删除原有缓存");
redisTemplate.opsForValue().set(tel, pyzm, 120, TimeUnit.SECONDS);
logger.info("新增一个缓存");
}catch (Exception e){
logger.info("缓存失败-原因:"+e.toString());
}
}
//设置模板中的2个参数 第一个为验证码yzm 第二个为2 (2分钟内输入验证码)
String[] datas= new String[]{pyzm,"2"};
logger.info("准备传入的参数"+tel+"==="+templateId+"====="+datas);
// 发送短信 获取发送结果
HashMap<String, Object> result = sdk.sendTemplateSMS(tel,templateId ,datas);
logger.info("短信验证发送结果 = " + result);
// statusCode状态码为000000,即为发送成功
if("000000".equals(result.get("statusCode"))){
// 正常返回输出data包体信息(map)
HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
// 获取data中的key
Set<String> keySet = data.keySet();
// 遍历key,通过key得到对应的值,输出
for(String key:keySet){
Object object = data.get(key);
logger.info(key +" = "+object);
}
}else{
//异常返回输出错误码和错误信息
logger.info("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
}
}
}
controller 短信注册
/**
* @Author: TianBo
* @Description: 接收表单参数,手机新用户注册
* @Date: 2020/6/4
* @Param postinfo: 自定义JAVA对象
* @Param request: 用于跳转至jsp页面
* @return: java.lang.String
**/
@RequestMapping(value = "/RegisterByPhone", method = RequestMethod.POST)
public String registerByPhone(postinfo postinfo,HttpServletRequest request) {
logger.info("传入参数" + postinfo);
String u = postinfo.getUsername();
String p = postinfo.getPassword();
String pp = postinfo.getAgainPassword();
String phone = postinfo.getPhone();
String InputYzm = postinfo.getYzm();
logger.info("用户输入的注册信息:" + "名字:" + u + " 密码:" + p + " 第二个密码:" + pp + " 手机号:" + phone + " 验证码:" + InputYzm);
//判断输入的用户名是否为空 或者 空字符
if (u != null && u != "") {
logger.info("用户名不为空");
} else {
String error = "用户名不能为空,请重新输入用户名";
logger.info("用户名不能为空,请重新输入用户名");
request.setAttribute("NameError", error);
return "phoneRegister";
}
if (p != null && p != "") {
logger.info("密码不为空");
} else {
String error = "用户密码不能为空!";
logger.info("用户密码不能为空!");
request.setAttribute("PassError", error);
return "phoneRegister";
}
if (pp != null && pp != "") {
logger.info("重复密码不为空");
} else {
String error = "重复密码不能为空!";
logger.info("重复输入密码不能为空!");
request.setAttribute("PassError", error);
return "phoneRegister";
}
if (p.equals(pp)) {
logger.info("两次输入密码一致");
} else {
String error = "两次输入密码不一致,请重新输入";
logger.info("两次输入密码不一致");
request.setAttribute("TwoPassError", error);
return "phoneRegister";
}
//判断数据库中是否有此用户名
MyAccount NameAccount = my.selectAccountByName(u);
logger.info("根据用户名查询出的用户为" + NameAccount);
//如果查询出的账户为空(代表用户不存在),才能注册
if (ObjectUtils.isEmpty(NameAccount)) {
logger.info("此用户名不存在,可以注册!");
} else {
String error = "用户名已经存在,请更换用户名注册或直接登录";
logger.info("用户名已经存在");
request.setAttribute("NameError", error);
return "phoneRegister";
}
if (phone != null && phone != "") {
logger.info("手机号不为空,可以注册");
} else {
String error = "手机号为空,请重新输入!";
logger.info("手机号为空");
request.setAttribute("PhoneError", error);
return "phoneRegister";
}
MyAccount PhoneAccount = my.selectAccountByPhone(phone);
logger.info("根据手机号查询出的用户为" + PhoneAccount);
//如果查询出的账户为空(代表用户不存在),才能注册
if (ObjectUtils.isEmpty(PhoneAccount)) {
logger.info("手机号未被注册过,可以注册!");
} else {
String error = "手机号已经被注册,请更换手机号或直接登录";
logger.info("手机号已经被注册");
request.setAttribute("PhoneError", error);
return "phoneRegister";
}
if (InputYzm != null && InputYzm != "") {
logger.info("输入的验证码不为空");
} else {
String error = "验证码为空,请输入验证码";
logger.info("输入的验证码为空");
request.setAttribute("YzmError", error);
return "phoneRegister";
}
//获取缓存中的验证么
String GetRedisYzm = (String) redisTemplate.opsForValue().get(phone);
logger.info("获取到的缓存里的验证码是"+GetRedisYzm);
if (GetRedisYzm != null) {
logger.info("缓存不为空,验证码还未到期");
if (InputYzm.equals(GetRedisYzm)){
logger.info("验证码相同");
MyAccount account = new MyAccount();
account.setUsername(u);
account.setPassword(p);
account.setPhone(phone);
logger.info("要注册的用户数据为:" + account);
try{
//插入数据
int id = my.insertAccount(account);
logger.info("注册完毕生成的用户id为"+id);
logger.info("注册成功!");
//返回到登录页面
return "login";
} catch (Exception e) {
String error = "注册失败,请再试试";
logger.info("注册失败,请重新输入");
request.setAttribute("error", error);
return "phoneRegister";
}
} else {
String error = "验证码错误,请重新输入!";
logger.info("验证码错误");
request.setAttribute("YzmError", error);
return "phoneRegister";
}
} else {
String error = "验证码为空,请重新输入!";
logger.info("验证码为空");
request.setAttribute("YzmError", error);
return "phoneRegister";
}}
SendCloud邮件
邮件jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>邮箱注册</title>
<body>
<strong><p>邮箱注册</p></strong>
<div "color:#6a8759;">"contain" >
<form action="/RegisterByEmail" method=POST >
请输入用户名:<br>
<input type="text" name="username" id="username" placeholder="请输入小于16位的用户名" maxlength="16">
${NameError}
<br>
请输入密码:<br>
<input type="text" name="password" id="pass" placeholder="请输入小于16位的密码" maxlength="16">
${PassError}
<br>
请再次确认密码:<br>
<input type="text" name="againPassword" id="againPass" placeholder="请再次输入密码" maxlength="16" >
${TwoPassError}
<br>
邮箱:<br>
<input type="text" name="email" id="email2" placeholder="请输入您的邮箱">
${EmailError}
<br>
请输入收到的验证码:<br>
<input type="text" name="yzm" id="yzm" placeholder="请输入4位验证码" maxlength="4">
<input type="button" name="" id="verCodeBtn" value="获取验证码" onclick="settime(this);"/>
${YzmError}
<br>
<br>
<input type="submit" value="注册">
</form>
</div>
<br>
<script src="http://www.lanrenzhijia.com/ajaxjs/jquery.min.js"></script>
<script>
//验证码
var counts = 120;
function settime(val) {
if(counts == 0) {
val.removeAttribute("disabled");
val.value = "获取验证码";
counts = 120;
return false;
} else {
val.setAttribute("disabled", true);
val.value = "重新发送(" + counts + ")";
counts--;
}
setTimeout(function() {
settime(val);
}, 1000);
}
//获取验证码
$(function(){
$("#verCodeBtn").click(function() {
var userinfo = {
"UserEmailNum": $("input[name='email']").val()
}
$.ajax({
url: "/sendEmailYzm",
data: userinfo,
type: "post",
});
});
})
</script>
</hr>
<a href="/RegisterByPhonePage">如果你想使用手机注册,请点击此处</a>
<br>
<a href="/login">已有账号?点此直接登录</a>
</body>
</html>
用spring管理账号密码
email.properties
URL=https://api.sendcloud.net/apiv2/mail/send
API_USER=tbtb_test_pVslgW
API_KEY=ZPE6CpBCT1mXJzTy
bean对象
<!-- 用Spring管理短信接口的bean对象-->
<bean id="sendMail" class="com.mb.util.SendMailUtil">
<constructor-arg name="url" value="${URL}"></constructor-arg>
<constructor-arg name="apiUser" value="${API_USER}"></constructor-arg>
<constructor-arg name="apiKey" value="${API_KEY}"></constructor-arg>
</bean>
发邮件工具类
public class SendMailUtil {
Logger logger = Logger.getLogger(SendMessageUtil.class);
@Autowired
RedisTemplate redisTemplate;
private String url;
private String apiUser;
private String apiKey;
public SendMailUtil(String url, String apiUser, String apiKey) {
this.url = url;
this.apiUser = apiUser;
this.apiKey = apiKey;
}
public void Send(String email) {
logger.info("输入的邮箱为:"+email);
//邮件标题
String subject = "新用户注册";
logger.info("邮件的主题为:"+subject);
//随机生成4位数验证码
int yzm = (int) ((Math.random() * 8999) + 1000);
//验证码转化为Strig类型e
String eyzm = String.valueOf(yzm);
logger.info("邮件验证码是:" + eyzm);
//验证码有效期
String limitTime="2";
logger.info("邮件验证码的有效期为"+limitTime+"分钟");
String html = "您的验证码是"+"["+eyzm+"]"+",请在"+limitTime+"分钟内输入!";
logger.info("邮件的内容为:"+html);
// 创建http客户端 (另一种方式:CloseableHttpClient httpclient = HttpClients.createDefault())
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建post请求
HttpPost httpPost = new HttpPost(url);
/** 先取出key为邮件名的缓存
* 如果没有缓存,就新增一个
*如果有缓存,就删除之前的缓存,再新增
*/
String EmailRedisResult = (String)redisTemplate.opsForValue().get(email);
if(EmailRedisResult==null){
try{
redisTemplate.opsForValue().set(email,eyzm,120, TimeUnit.SECONDS);
logger.info("放入缓存成功");
}catch (Exception e){
logger.info("新增缓存失败"+e.toString());
}
}else {
try{
redisTemplate.delete(email);
logger.info("删除原有缓存成功");
redisTemplate.opsForValue().set(email,eyzm,120, TimeUnit.SECONDS);
logger.info("放入缓存成功");
}catch (Exception e){
logger.info("更新缓存失败"+e.toString());
}
}
/**
* 定义了一个list,该list的数据类型是NameValuePair(简单名称值对节点类型),
* 这个代码用于Java像url发送Post请求。在发送post请求时用该list来存放参数。
*/
List<NameValuePair> params = new ArrayList<NameValuePair>();
//API_USER
params.add(new BasicNameValuePair("apiUser", apiUser));
//API_KEY
params.add(new BasicNameValuePair("apiKey", apiKey));
//收件人地址. 多个地址使用 ; 分隔, 如 ben@ifaxin.com;joe@ifaxin.com
params.add(new BasicNameValuePair("to", email));
//发件人地址. 建议from域名后缀与发信域名一致。
params.add(new BasicNameValuePair("from", "support@ifaxin.com"));
//发件人名称
params.add(new BasicNameValuePair("fromName", "JnShu"));
//邮件标题
params.add(new BasicNameValuePair("subject", subject));
//邮件内容
params.add(new BasicNameValuePair("html", html));
logger.info("向邮箱API传入的参数为"+params);
try {
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 由客户端执行(发送)Post请求
HttpResponse response = httpClient.execute(httpPost);
//判定返回的reponse结果是否为 ok
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
logger.info("发送状态:"+EntityUtils.toString(response.getEntity()));
} else {
System.err.println("error");
logger.info("未收到服务端返回的消息!");
}
}catch (UnhandledException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
//释放底层的httpConnection,以便可以重用请求
httpPost.releaseConnection();
}
}
controller层邮件注册
/**
* @Author: TianBo
* @Description: 接收表单参数,手机新用户注册
* @Date: 2020/6/4
* @Param postinfo: 自定义JAVA对象
* @Param request: 用于跳转jsp页面
* @return: java.lang.String
**/
@RequestMapping(value = "/RegisterByEmail", method = RequestMethod.POST)
public String registerByEmail(postinfo postinfo,HttpServletRequest request) {
logger.info("传入参数" + postinfo);
String u = postinfo.getUsername();
String p = postinfo.getPassword();
String pp = postinfo.getAgainPassword();
String email = postinfo.getEmail();
String InputYzm = postinfo.getYzm();
logger.info("用户输入的注册信息:" + "名字:" + u + " 密码:" + p + " 第二个密码:" + pp + " 邮箱:" + email + " 验证码:" + InputYzm);
//判断输入的用户名是否为空 或者 空字符
if (u != null && u != "") {
logger.info("用户名不为空");
} else {
String error = "用户名不能为空,请重新输入用户名";
logger.info("用户名不能为空,请重新输入用户名");
request.setAttribute("NameError", error);
return "emailRegister";
}
if (p != null && p != "") {
logger.info("密码不为空");
} else {
String error = "用户密码不能为空!";
logger.info("用户密码不能为空!");
request.setAttribute("PassError", error);
return "emailRegister";
}
if (pp != null && pp != "") {
logger.info("重复密码不为空");
} else {
String error = "重复密码不能为空!";
logger.info("重复输入密码不能为空!");
request.setAttribute("PassError", error);
return "emailRegister";
}
if (p.equals(pp)) {
logger.info("两次输入密码一致");
} else {
String error = "两次输入密码不一致,请重新输入";
logger.info("两次输入密码不一致");
request.setAttribute("TwoPassError", error);
return "emailRegister";
}
//判断数据库中是否有此用户名
MyAccount NameAccount = my.selectAccountByName(u);
logger.info("根据用户名查询出的用户为" + NameAccount);
//如果查询出的账户为空(代表用户不存在),才能注册
if (ObjectUtils.isEmpty(NameAccount)) {
logger.info("此用户名不存在,可以注册!");
} else {
String error = "用户名已经存在,请更换用户名注册或直接登录";
logger.info("用户名已经存在");
request.setAttribute("NameError", error);
return "emailRegister";
}
if (email != null && email != "") {
logger.info("邮箱号不为空,可以注册");
} else {
String error = "邮箱号为空,请重新输入!";
logger.info("邮箱号为空");
request.setAttribute("EmailError", error);
return "emailRegister";
}
MyAccount EmailAccount = my.selectAccountByEmail(email);
logger.info("根据邮箱号查询出的用户为" + EmailAccount);
//如果查询出的账户为空(代表用户不存在),才能注册
if (ObjectUtils.isEmpty(EmailAccount)) {
logger.info("邮箱号未被注册过,可以注册!");
} else {
String error = "邮箱号已经被注册,请更换新邮箱或直接登录";
logger.info("邮箱号已经被注册");
request.setAttribute("EmailError", error);
return "phoneRegister";
}
if (InputYzm != null && InputYzm != "") {
logger.info("输入的验证码不为空");
} else {
String error = "验证码为空,请输入验证码";
logger.info("输入的验证码为空");
request.setAttribute("YzmError", error);
return "phoneRegister";
}
//获取缓存中的验证么
String GetRedisYzm = (String) redisTemplate.opsForValue().get(email);
logger.info("获取到的缓存里的验证码是"+GetRedisYzm);
if (GetRedisYzm != null) {
logger.info("缓存不为空,验证码还未到期");
if (InputYzm.equals(GetRedisYzm)){
logger.info("验证码相同");
MyAccount account = new MyAccount();
account.setUsername(u);
account.setPassword(p);
account.setEmail(email);
logger.info("要注册的用户数据为:" + account);
try{
//插入数据
int id = my.insertAccount(account);
logger.info("注册完毕生成的用户id为"+id);
logger.info("注册成功!");
//返回到登录页面
return "login";
} catch (Exception e) {
String error = "注册失败,请再试试";
logger.info("注册失败,请重新输入");
request.setAttribute("error", error);
return "phoneRegister";
}
} else {
String error = "验证码错误,请重新输入!";
logger.info("验证码错误");
request.setAttribute("YzmError", error);
return "phoneRegister";
}
} else {
String error = "验证码为空,请重新输入!";
logger.info("验证码为空");
request.setAttribute("YzmError", error);
return "phoneRegister";
}
}
}
评论