通过短信验证码修改密码

1.前端页面ftl

<#import "/WEB-INF/freemarker_include/base.ftl" as base/>
<!DOCTYPE html>

<#assign basePath=request.contextPath>
<html lang="zh-cn">
<head><@base.head/>
</head>

<body class="background-white" style="overflow: hidden;">
<div id="container" class="ph-container"
style="padding: 5px; overflow-y: auto;">
<div class="ph-content layout-fill" style="padding: 5px;">
<form id="edit_form" class="form-horizontal ph-form"
action="commonUser!updateChangePassword.action" method="post">
<table style="width: 100%; font-size: 12px; min-width: 400px;"
class="table table-hover ph-info-table">
<thead>
<tr>
<th colspan="3" class="ph-info-title"><i
class="fa fa-angle-up"></i>修改密码</th>
</tr>
</thead>
<tbody>
<tr>
<td width="150" class="ph-info-label"><span
class="ph-txt-impt">*</span>账号:</td>
<td width="220" class="ph-info-value"><input type="Text"
placeholder="" name="paramMap.userName" id="user_name"
class="form-text required" value=""></td>
<td class="ph-info-value">&nbsp;</td>
</tr>
<tr>
<td width="150" class="ph-info-label"><span
class="ph-txt-impt">*</span>手机号:</td>
<td width="220" class="ph-info-value"><input type="text"
placeholder="请输入手机号" name="mobile" maxlength="11" id="mobile"
class="form-text required" value=""></td>
<td style="padding-left: 20px;"><input
class="ph-btn-default" type="button" name="paramMap.verCodeBtn"
id="paramMap_verCodeBtn" value="获取验证码" onclick="setTime(this)" /><span
id="show_time"></span></td>
</tr>
<tr>
<td width="150" class="ph-info-label"><span
class="ph-txt-impt">*</span>验证码:</td>
<td width="220" class="ph-info-value"><input type="Text"
placeholder="请输入验证码" name="paramMap.verCode" maxlength="6"
id="paramMap_verCode" class="form-text required" value=""></td>
<td class="ph-info-value">&nbsp;</td>
</tr>
<tr>
<td class="ph-info-label"><span class="ph-txt-impt">*</span>新密码:
</td>
<td class="ph-info-value"><input type="password"
placeholder="" name="paramMap.userPassword" id="user_password"
class="form-text required" value=""></td>
<td class="ph-info-value" style="padding-left: 30px;">密码长度不低于八位,大写字母、小写字母、数字、字符包含三点以上,不能包含用户名。区分大小写</td>
</tr>
<tr>
<td class="ph-info-label"><span class="ph-txt-impt">*</span>再次输入新密码:
</td>
<td class="ph-info-value"><input type="password"
placeholder="" name="passwordConfirm" id="password_confirm"
class="form-text required" value=""></td>
<td class="ph-info-value" style="padding-left: 30px;">请再次填写密码</td>
</tr>
<tr>
<td class="ph-info-label">&nbsp;</td>
<td class="ph-info-value">
<button type="submit" class="ph-btn-default"
style="padding-left: 30px; padding-right: 30px;">保存</button>
</td>
<td class="ph-info-value" style="padding-left: 30px;">&nbsp;</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>

<@base.baseJavascript/>
<script src="../js/phssh/sys/user_updatechangePassword.js"
type="text/javascript"></script>
<script src="../js/phssh/sys/md5.js" type="text/javascript"></script>
<script src="../js/phssh/sys/jquery.base64.js" type="text/javascript"></script>

<script type="text/javascript">
//验证码
var counts = 120;
var sendTag = '0';
var setTimeoutTag = undefined;
function setTime(val) {
var mobile = $('#mobile').val();
var userName = $('#user_name').val();
if(null == userName || '' == userName){
alert('请输入要修改密码的工号...');
return false;
}
if (('' == mobile || undefined == mobile) || mobile.length != 11) {
alert('请输入正确的手机号码...');
return false;
}
if ('0' == sendTag) {
// 获取短信验证码
getCodeStr(mobile,userName);
}
if (counts == 0) {
val.removeAttribute("disabled");
val.value = "获取验证码";
counts = 120;
sendTag = tag;
clearTimeout(setTimeoutTag);
} else {
sendTag = '1';
val.setAttribute("disabled", 'disabled');
val.value = "重新发送(" + counts + ")";
counts--;
}
setTimeoutTag = setTimeout(function() {
setTime(val);
}, 1000);
}

// 到后台获取短信验证码
function getCodeStr(mobile,userName) {
$.ajax({
type : 'post',
dataType : 'json',
url : "sendVer.action",
data : {
'paramMap.mobile' : mobile,
'paramMap.userName' : userName
},
success : function(data) {
if('200' == data.statusCode){
alert("验证码发送成功...");
}else{
alert("验证码发送失败" + data.message + "...");
}
},
error : function() {
alert("发送失败...");
}
});
}

$('#edit_form').submit(function() {
if ($('#paramMap_verCode').val() == '') {
alert('请输入验证码');
return false;
}
if ($('#user_password').val() == '') {
alert('请输入新密码');
return false;
}
if ($('#user_password').val() != $('#password_confirm').val()) {
alert('两次输入的密码不一致,请重新输入');
return false;
}
$.ajax({
type : 'post',
dataType : 'json',
url : 'chackVerifi.action',
data : {
'paramMap.verCode' : $("#paramMap_verCode").val(),
'paramMap.userName' : $("#user_name").val(),
'paramMap.mobile' : $("#mobile").val(),
'paramMap.userPassword' : $("#user_password").val()
},
success : function(data) {
if ('200' == data.statusCode) {
alert("密码修改成功!!!");
window.location.href = "loginP.action";
} else {
alert("操作失败..." + data.message);
}
}
});
return false;
});
</script>
</body>

</html>

2.PO

@Getter
@Setter
@Entity
@Table(name = "SYS_SEND_VER")
public class SendVer {

/** ID */
@Id
@GenericGenerator(name = "objectIdGenerator", strategy = "com.powerhua.phssh.po.id.ObjectIdGenerator")
@GeneratedValue(generator = "objectIdGenerator")
@Column(name = "ID", unique = true, nullable = false, length = 24)
private String id;

// 用户工号
@Column(name = "user_name")
private String userName;

// 手机号码
@Column(name = "mobile")
private String mobile;

// 验证码
@Column(name = "code_Str")
private String codeStr;

// 发送时间
@Column(name = "send_Time", updatable = false)
protected Timestamp sendTime = new Timestamp(System.currentTimeMillis());

}

3.发送短信校验码,校验数据库校验码

// 发送短信验证码
public String sendVer() {
log.info("发送短信验证码进来了..." + "手机号码:" + paramMap.get("mobile") + " 工号:"
+ paramMap.get("userName"));
String statusCode = JsonResult.STATUS_CODE_FAIL;
String msg = "";
try {
// 生产随机数验证码
int verificationCode = (int) ((Math.random() * 9 + 1) * 100000);
log.info("验证码是:" + verificationCode);
String mobile = paramMap.get("mobile");
String userName = paramMap.get("userName");
if (StringUtils.isEmpty(mobile)) {
throw new Exception("手机号码为空,验证失败.");
}
if (StringUtils.isEmpty(userName)) {
throw new Exception("用户工号为空,验证失败.");
}
List<User> userList = baseService.queryByHql(
"from User u where u.isValid='1' and u.userName=?",
userName);
if (null == userList || userList.isEmpty()) {
throw new Exception("用户工号不存在,验证失败.");
}
// 发送短信验证码
String resXml = SmsUtils.sendVer(mobile, verificationCode + "");
if(StringUtils.isEmpty(resXml)){
throw new Exception("发送验证码失败.");
}
log.info("发送短信验证码返回结果:" + resXml);
if (StringUtils.isNotEmpty(resXml)) {
Document document = DocumentHelper.parseText(resXml);
Element root = document.getRootElement();
String status = root.selectSingleNode("//status").getText();
log.info(status);
// 记录发送短信验证码日志
SendVer addSendVer = new SendVer();
addSendVer.setCodeStr(verificationCode + "");
addSendVer.setMobile(mobile);
addSendVer.setUserName(userName);
addSendVer
.setSendTime(new Timestamp(System.currentTimeMillis()));
baseService.save(addSendVer);
statusCode = JsonResult.STATUS_CODE_SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
}
jsonResult = new JsonResult(statusCode, msg);
return SUCCESS;
}

//校验验证码
public String chackVerifi() {
String statusCode = JsonResult.STATUS_CODE_FAIL;
String msg = "";
try {
log.info("修改密码验证码入参:" + paramMap);
// 获取数据
String verCode = paramMap.get("verCode");
String userName = paramMap.get("userName");
String mobile = paramMap.get("mobile");
String userPassword = paramMap.get("userPassword");
// 校验用户是否存在
List<User> userList = baseService.queryByHql(
"from User u where u.isValid='1' and u.userName=?",
userName);
if (null == userList || userList.isEmpty()) {
throw new Exception("用户工号不存在,修改密码失败.");
}

// 判断验证码是否正确
String hql = " from SendVer s where s.userName = ? and s.mobile=? and s.codeStr = ? order by sendTime desc ";
List<SendVer> list = baseService.queryByHql(hql, userName, mobile,
verCode);
if (null == list || list.isEmpty()) {
throw new Exception("验证码不存在,修改密码失败...");
}
// 判断是否过期、时间必须是两分钟内
SendVer existsVer = list.get(0);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
long timeCount = currentTime.getTime()
- existsVer.getSendTime().getTime();
// 时间超过120秒
if ((timeCount / 1000) > 120) {
throw new Exception("验证码已超时,请重试...");
}
// 验证通过 修改密码
User updateUser = userList.get(0);
if(null != updateUser){
updateUser.setUserPassword(DigestUtils.md5Hex(userPassword));
baseService.update(updateUser);
log.info("修改密码成功....");
statusCode = JsonResult.STATUS_CODE_SUCCESS;
}
} catch (Exception e) {
msg = e.getMessage();
e.printStackTrace();
}
jsonResult = new JsonResult(statusCode, msg);
return SUCCESS;
}

4.发送短信验证码接口

//发送验证码
public static String sendVer(String mobile,String verificationCode){
String resXml = "";
try {
String contents1 = "您登录海南电信无纸化系统的验证码为"+verificationCode+
"该验证码仅限使用一次且在2分钟内有效。"+
"--升级电信智能宽带,更快、更稳、更智能!";
String appMessageID = ((long)(Math.random()*1000000000))+"" ;

//发送验证码接口url
String url = "http://?.?.?.?:8080/axis2/services/SmsService?****";
InputStream is = SmsUtils.class.getResourceAsStream("/com/***/webservice/client/sms/sms_req.xml");
String xmlStr = HttpConnectionCall.getByteByStream(is, "UTF-8");
xmlStr = xmlStr.replace("#AuthenticatorClient", getAuthent())
.replace("#TimeStamp", timeStamp)
.replace("#appMessageID", appMessageID)
.replace("#destTermID", mobile)
.replace("#msgContent", contents1);
resXml = HttpConnectionCall.execute(url, xmlStr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resXml;

}

5.sms_req.xml配置文件

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:axis="http://ws.apache.org/axis2">
<soapenv:Header />
<soapenv:Body>
<axis:sendMessage>
<ClientID>wzh</ClientID>
<AuthenticatorClient>#AuthenticatorClient</AuthenticatorClient>
<TimeStamp>#TimeStamp</TimeStamp>
<Message>
<appMessageID>#appMessageID</appMessageID>
<destTermID>#destTermID</destTermID>
<msgContent>#msgContent</msgContent>
<msgLevel>0</msgLevel>
<sendMan></sendMan>
<spCode>10001</spCode>
</Message>
</axis:sendMessage>
</soapenv:Body>
</soapenv:Envelope>

猜你喜欢

转载自www.cnblogs.com/94-181227/p/10899939.html