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"> </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"> </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"> </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;"> </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>
------------------------------------------------------
md5加密:DigestUtils.md5Hex("********");
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
paraStr = gson.toJson(obj).toString();