controller里写的
@RequestMapping({"/createValidateCode"})
public void verification(HttpServletRequest request,HttpServletResponse response) {
try {
this.responseCrossDomain(response);
String mobile = this.assService.get(this.getCurrentAss().getId()).getSafeTelephone();
if (StringUtils.isEmpty(mobile)) {
this.renderJson(response, false,AppConst.REQUEST_400,"验证码错误请重新输入!");
return;
}
if (! CommonUtils.mobileFormat(mobile)) {
this.renderJson(response, false,AppConst.REQUEST_400,"手机号格式不正确");
return;
}
HttpSession httpSession = request.getSession();
if (httpSession.getAttribute("validateTime001") != null) {
long preTime = (Long) httpSession.getAttribute("validateTime001");
long currentTime = System.currentTimeMillis();
if ((currentTime - preTime) <= 60 * 1000) {// 小于1分钟
this.renderJson(response, false,AppConst.REQUEST_400,"验证码发送太频繁[小于60秒]");
return;
}
}
//
// 发送验证码短信
String verifyCode = smsMessageService.generateVerifyCode();
logger.info("ass band safe mobile: ["+mobile+"],create verifyCode:" + verifyCode + "】");
ShortMsg msg = smsMessageService.sendVerifyCodeMsgAlibaba(ShortmsgConstApp.ASS_CASH_TID, mobile, verifyCode);
if (null==msg) {
this.outputFail(response, AppConst.REQUEST_400, "验证码发送失败");
return;
} else if(msg.getStatus().intValue()==0){
if("160040".equals(msg.getResultCode())){
msg.setResultMsg("当天发送次数已达上限!");
}
this.outputFail(response, AppConst.REQUEST_400, msg.getResultMsg());
return;
}
httpSession.setAttribute("mobileandvc", mobile + "," + verifyCode);
httpSession.setAttribute("validateTime001", System.currentTimeMillis());
AppSessionContext.addSession(httpSession);
JSONObject result = new JSONObject();
result.put("sessionId", httpSession.getId());
this.renderJson(response, true,AppConst.REQUEST_200,httpSession.getId());
} catch (Exception e) {
logger.error("【获取注册验证码】出现异常:" + e.getMessage());
}
}
@RequestMapping({"mobileBand"})
public String mobileBand(HttpServletRequest request,
HttpServletResponse response, Model model) {
new ShopAss();
ShopAss ass = this.assService.get(this.getCurrentAss().getId());
new ShopAss();
ShopAss assAccount = this.assService.get(this.getCurrentAss().getId());
model.addAttribute("assAccount", assAccount);
return "ass/mobile_band";
}
@RequestMapping({"saveBandMobile"})
public String saveBandMobile(HttpServletRequest request,
HttpServletResponse response, Model model) {
new ShopAss();
String oldMobile = request.getParameter("oldMobile");
String newMobile = request.getParameter("newMobile");
String mobileSmsCode = request.getParameter("mobileSmsCode");
ShopAss assAccount = this.assService.get(this.getCurrentAss().getId());
model.addAttribute("assAccount", assAccount);
String regExp = "^[1][34578][0-9]{9}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(newMobile);
HttpSession httpSession = AppSessionContext.getSession(request.getSession().getId());
String codes = (String) httpSession.getAttribute("mobileandvc");
String code2[] = codes.split(",");
if (!StringUtils.isEmpty(request.getParameter("oldMobile"))
&& !StringUtils.isEmpty(request
.getParameter("newMobile"))
&& !StringUtils.isEmpty(request.getParameter("mobileSmsCode"))) {
if (!oldMobile.equals(assAccount.getSafeTelephone())) {
return this.renderJson(response, false, AppConst.REQUEST_400,
"绑定的旧手机号输入错误!");
}else if(!m.find()) {
return this.renderJson(response, false, AppConst.REQUEST_400,
"手机号格式不正确");
}else if(oldMobile.equals(code2[0]) || mobileSmsCode.equals(code2[1])) {
assAccount.setSafeTelephone(newMobile);
this.assService.saveTel(assAccount);
return this.renderJson(response, true, AppConst.REQUEST_200,
"新手机号绑定成功!");
}else {
return this.renderJson(response, false, AppConst.REQUEST_400,
"验证码填写错误!");
}
}else {
return this.renderJson(response, false, AppConst.REQUEST_400,
"旧手机号/新手机号/短信验证都不能为空!");
}
}
service 类
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.epay.opt.sys.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.epay.common.config.Global;
import com.epay.common.persistence.Page;
import com.epay.common.service.CrudService;
import com.epay.common.utils.VerifyCodeApp;
import com.epay.opt.sys.dao.ShortMsgDao;
import com.epay.opt.sys.entity.ShortMsg;
@Service
@Transactional(readOnly = true)
public class ShortMsgService extends CrudService<ShortMsgDao, ShortMsg> {
private static Logger LOGGER = LoggerFactory.getLogger(ShortMsgService.class);
/**
* 生成六位随机数
* @return String
*/
public String generateVerifyCode(){
return VerifyCodeApp.getRandNum(6);
}
public ShortMsg get(String id) {
return super.get(id);
}
public List<ShortMsg> findList(ShortMsg shortMsg) {
return super.findList(shortMsg);
}
public Page<ShortMsg> findPage(Page<ShortMsg> page, ShortMsg shortMsg) {
return super.findPage(page, shortMsg);
}
@Transactional(readOnly = false)
public void save(ShortMsg shortMsg) {
super.save(shortMsg);
}
@Transactional(readOnly = false)
public void delete(ShortMsg shortMsg) {
super.delete(shortMsg);
}
/*
* 用到阿里巴巴短信服务平台发送短信
*/
@Transactional(readOnly = false)
public ShortMsg sendVerifyCodeMsgAlibaba(String tid, String mobile, String code) {
try {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Global.getConfig("ALIYUN.SMS.ACCESSKEYID"), Global.getConfig("ALIYUN.SMS.ACCESSKEYSECRET"));
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", Global.getConfig("ALIYUN.SMS.PRODUCT"), Global.getConfig("ALIYUN.SMS.DOMAIN"));
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(mobile);
//必填:短信签名-可在短信控制台中找到
request.setSignName(Global.getConfig("ALIYUN.SMS.SIGN_NAME"));
//必填:短信模板-可在短信控制台中找到
String[] TEMPLATE_CODE = Global.getConfig("ALIYUN.SMS.TEMPLATE_CODE_LIST").split(",");
String randomTemplateCode = "";
int index = (int) (Math.random() * TEMPLATE_CODE.length);
randomTemplateCode = TEMPLATE_CODE[index];
request.setTemplateCode(randomTemplateCode);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam("{\"name\":\""+mobile+"\", \"code\":\""+code+"\"}");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
request.setOutId(mobile+sdf.format(new Date()));
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
LOGGER.info("aliyun return params:"+JSON.toJSONString(sendSmsResponse));
String statusCode = sendSmsResponse.getCode();
String statusMsg = sendSmsResponse.getMessage();
String smsMessageSid = randomTemplateCode;
Date sendTime = new Date();
int status = 0;
if ("OK".equals(statusCode)) {//正常返回输出data包体信息(map)
statusMsg = "发送成功-"+code;
status = 1;
} else {//异常返回输出错误码和错误信息
statusMsg = "短信发送失败,请联系管理员!";
status = 0;
}
ShortMsg shortmsg = new ShortMsg();
shortmsg.setIsNewRecord(true);
shortmsg.setResultCode(statusCode);
shortmsg.setMobile(mobile);
shortmsg.setResultMsg(statusMsg);
shortmsg.setStatus(status);
shortmsg.setSendTime(sendTime);
shortmsg.setSmsSid(smsMessageSid);
shortmsg.setTemplateId(tid);
this.save(shortmsg);
// if (status == 0) {
// return false;
// }
return shortmsg;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
jsp页面
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@taglib uri="http://www.opensymphony.com/sitemesh/page" prefix="smp"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<smp:apply-decorator name="assPanel">
<html>
<head>
<title>修改个人绑定手机号码</title>
<link href="${ctxStatic}/common/jeesite.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
function ajaxChangeMobile(){
var oldMobile = $('#oldMobile').val();
var newMobile=$("#newMobile").val();
var mobileSmsCode=$("#mobileSmsCode").val();
if(oldMobile==''||newMobile==''||mobileSmsCode==''){
layer.open({title: '警告',content:'旧手机号/新手机号/短信验证都不能为空!'});
}
var oks = jqueryAjaxPost({
"oldMobile":oldMobile,
"newMobile":newMobile,
"mobileSmsCode":mobileSmsCode
}, "${ctx_root}/ass/workspace/saveBandMobile");
var data = oks;
console.log(data);
if (!data.success) {
layer.open({title: '警告',content:data.message});
return false;
}else{
layer.open({title: '成功',content:data.message});
location.href = '${ctx_root}/ass/workspace/mobileBand';
}
};
$(function(){
$("input[type='submit']").attr('disabled',true);
$("#btn-sms").click(function(){
if(!check_mobile())
{
return false;
}
$('#btn-sms').addClass('disable');
$('#btn-sms').attr('disabled',true);
sendSMS();
});
});
function sendSMS(){
if(check_mobile()){
$.ajax({
type: "GET",
url: '${ctx_root}/ass/workspace/createValidateCode?rnd='+new Date().getTime()/1000,
data:'oldMobile='+$.trim($('#oldMobile').val()),
dataType: 'json',
success: function(data)
{
if(data.success){
lSeconds=60;
$("#btn-sms").attr('value','已成功发送');
displayInterval();
}
else{
alert(data.message);
$('#btn-sms').removeClass('disable');
$('#btn-sms').attr('disabled',false);
}
},
'error':function(){
alert('获取短信出错,请重试或联系管理员!');
$('#btn-sms').removeClass('disable');
$('#btn-sms').attr('disabled',false);
}
});
}
}
//手机验证
function check_mobile()
{
var m=$.trim($('#oldMobile').val());
if(m!='')
{
var reg = /^1[34578]\d{9}$/;
var result = false;
if (reg.test(m))
result=true;
if (result)
{
return true;
}else{
alert("请输入正确的手机号");
return false;
}
}else{
alert("请输入手机号");
return false;
}
}
function popPolicy()
{
$.fancybox.open({
'type' : 'inline',
'href': '#policy-dialog'
});
}
function hasRead()
{
if($('#cbkRead').is(":checked"))
{
$("input[type='submit']").attr('disabled',false);
}
else
{
$("input[type='submit']").attr('disabled',true);
}
}
/*
$( "#CustomerAccount" ).blur(function() {
$.ajax({
type: "POST",
url: 'Customers/validateField',
data: {'account':$("#CustomerAccount").val()},
success: function(data)
{
$('#flashError').html(data);
}
});
});
$( "#CustomerPassword" ).blur(function() {
$.ajax({
type: "POST",
url: 'Customers/validateField',
data: {'password':$("#CustomerPassword").val()},
success: function(data)
{
$('#flashError').html(data);
}
});
});
$( "#CustomerVerifyPassword" ).blur(function() {
$.ajax({
type: "POST",
url: 'Customers/validateField',
data: {'verify_password':$("#CustomerVerifyPassword").val(), 'password':$("#CustomerPassword").val()},
success: function(data)
{
$('#flashError').html(data);
}
});
});
*/
var lSeconds = 60;
function displayInterval(){
$("#btn-sms").unbind('click');
timeIntervalSMS=setInterval(function(){
if(lSeconds<=1){
$('#btn-sms').removeClass('disable');
$('#btn-sms').attr('disabled',false);
$("#btn-sms").attr('value','重新发送');
clearInterval(timeIntervalSMS);
$("#btn-sms").click(function(){
$('#btn-sms').addClass('disable');
$('#btn-sms').attr('disabled',true);
sendSMS();
});
return;
}
lSeconds--;
$('#btn-sms').addClass('disable');
$("#btn-sms").attr('value',lSeconds+"秒后重发");
}, 1000);
}
</script>
<style type="text/css">
.disable{
color:#999!important;
}
.sendMessage {
cursor: pointer;
width: 90px;
height: 30px;
border: 2px solid #ececec;
background: #f4f4f4;
display: block;
color: #333;
font-size: 12px;
text-align: center;
line-height: 30px;
margin-left:10px;
}
</style>
</head>
<body>
<div class="page-content">
<div class="panel panel-default clearfix marginbot20 pctopbg">
<ul id="generalTab" class="nav nav-tabs ul-edit responsive hidden-xs hidden-sm" style="left: 0px;">
<li class=""><a href="#alert-tab" data-toggle="tab">账户明细</a></li>
<li class=""><a href="${ctx_root}/ass/workspace/modifyPwd" data-toggle="tab" >登入密码</a></li>
<li class=""><a href="${ctx_root}/ass/workspace/modifyPay" data-toggle="tab" >支付密码</a></li>
<li class=""><a href="${ctx_root}/ass/workspace/assinfo" data-toggle="tab">个人信息</a>
<li class="active"><a href="${ctx_root}/ass/workspace/mobileBand" data-toggle="tab">手机绑定</a>
</ul>
<div id="generalTabContent" class="tab-content responsive hidden-xs hidden-sm">
<div id="note-tab" class="tab-pane fade active in">
<!--这是查询模块开始-->
<div class="panel panel-default clearfix">
<div class="panel-body">
<!--这是新增-->
<div id="addPayPwd">
<form id="inputForm" modelAttribute="user" action="${ctx_root}/ass/workspace/saveBandMobile" method="post" class="form-horizontal">
<c:if test="${success==false}">
<label id="loginError" class="error">${message}</label>
</c:if>
<c:if test="${success==true}">
<label id="loginError" class="success">${message}</label>
</c:if>
<div class="control-group">
<label class="control-label">旧手机号:</label>
<div class="controls">
<input id="oldMobile" name="oldMobile" value="${assAccount.safeTelephone }" type="text" value="" style="width:200px;float:left;" class="form-control required"/>
<span class="help-inline"><font color="red"> *(必填)</font> </span>
</div>
</div>
<div class="control-group">
<label class="control-label">新手机号:</label>
<div class="controls">
<input id="newMobile" name="newMobile" type="text" value="" style="width:200px;float:left;" class="form-control required"/>
<span class="help-inline"><font color="red"> *(必填)</font> </span>
</div>
</div>
<div class="control-group">
<label class="control-label">短信验证:</label>
<div class="controls">
<input id="mobileSmsCode" name="mobileSmsCode" type="text" value="" style="width:200px;float:left;" class="form-control required"/>
<input type="button" id="btn-sms" class="sendMessage" value="获取短信" />
</div>
</div>
<div class="form-actions">
<input id="btnSubmit" class="btn btn-primary" type="button" οnclick="ajaxChangeMobile()" value="确定绑定手机号"/>
</div>
</form>
</div>
</div>
</div>
</div>
<!--End CONTENT-->
</div>
</body>
</html>
</smp:apply-decorator>