最近一直在进行springboot的项目,前一阵子项目组接手了一个SSM项目,需要实现手机短信验证的相关功能。于是自己进行了重操,整合了网上的一些现有案例,重新编写这个功能。毕竟本人是个强迫症,喜欢把事情做到完美。废话不多说,开搞吧。
这里我使用的是IDEA创建的项目,跟ecplis/myecplise都大同小异,这里我就不过多介绍了。
首先我们创建一个Mavne项目
Emmmmm…剩下的我就不多说了,创建项目啥的这都是小事情了。
来看一下目录结构:
SSM基本配置就是这样。这时候就会有人问了,为啥XML的文件名跟网上不一样啊。这里我说一点,名字啥的无所谓,只要你里面的内容配置对了,系统能够通过你的文件访问到Dao层,service层,以及Controller层的路径就OK了。
一般我的spring-dao.xml 都会被 写成applicationContext.xml。所以这都无关紧要的,不过严谨一点还是比较好的。
JSP代码
我这里使用的boostrap,美化起来还是很nice的。不会的同学可以学习一下。
login.jsp
<%--
Created by IntelliJ IDEA.
User: 吾有所念人
Date: 2019/11/28
Time: 9:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link rel="stylesheet" href="../../static/css/bootstrap.min.css" />
<link rel="stylesheet" href="../../static/css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="../../static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../static/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="../../static/css/login.css" />
<meta charset="utf-8" />
<title>登录</title>
<script src="../../static/js/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function() {
$(".form").slideDown(500);
$("#landing").addClass("border-btn");
$("#registered").click(function() {
$("#landing").removeClass("border-btn");
$("#landing-content").hide(500);
$(this).addClass("border-btn");
$("#registered-content").show(500);
})
$("#landing").click(function() {
$("#registered").removeClass("border-btn");
$("#registered-content").hide(500);
$(this).addClass("border-btn");
$("#landing-content").show(500);
})
$("#phonelogin").click(function() {
window.location.href="/user/phonelogin"
})
$("#forgotpassword").click(function () {
window.location.href="/user/updatepwd"
})
});
</script>
</head>
<body style="background: url(../../static/img/bj1.jpg); background-size:cover;">
<div class="form" style="background-color:rgba(255,255,255,0.9);">
<form action="/user/checkLogin" method="post">
<div id="landing">登陆</div>
<div id="registered">注册</div>
<div class="fix"></div>
<div id="landing-content">
<div id="photo"><img src="../../static/img/photo.jpg" /></div>
<div class="inp"><input type="text" name="usercode" id="usercode" placeholder="用户名" /></div>
<div class="inp"><input type="password" name="userpwd" id="userpwd" placeholder="密码" /></div>
<%--<input class="login" type="submit" value="登录">--%>
<button type="submit" class="btn btn-success" id="login">登录</button>
<div id="bottom">
<%--<span id="phonelogin">手机登录</span>--%>
<button type="button" class="btn btn-primary" id="phonelogin">手机登录</button>
<%--<span id="forgotpassword">忘记密码</span>--%>
<button type="button" class="btn btn-primary" id="forgotpassword">忘记密码</button>
</div>
</div>
</form>
<form>
<div id="registered-content">
<div class="inp"><input type="text" placeholder="请输入用户名" /></div>
<div class="inp"><input type="password" placeholder="请输入密码" /></div>
<div class="inp"><input type="password" placeholder="请再次输入密码" /></div>
<div class="inp"><input type="text" placeholder="电子邮箱" /></div>
<button type="submit" class="btn btn-success" id="login">完成注册</button>
<br><br>
<div id="allregister">
<button type="submit" class="btn btn-primary">邮箱验证注册</button>
<a href="/user/phoneregister" class="btn btn-primary">手机短信注册</a>
</div>
<%--<input class="login" type="submit" value="注册">--%>
</div>
</form>
</div>
</body>
</html>
phonelogin.jsp (这是需要我们短信验证的jsp了)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>手机登录</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<link rel="stylesheet" href="../../static/css/style.css" />
<link rel="stylesheet" href="../../static/css/bootstrap.min.css" />
<link rel="stylesheet" href="../../static/css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="../../static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../static/js/bootstrap.min.js"></script>
</head>
<script type="text/javascript">
var InterValObj; //timer变量,控制时间
var count = 30; //间隔函数,1秒执行
var curCount;//当前剩余秒数
function sendMessage() {
curCount = count;
$("#btn").attr("disabled", "true");
$("#btn").val(curCount + "秒后可重新发送");
InterValObj = window.setInterval(SetRemainTime, 1000);
//启动计时器,1秒执行一次请求,发送验证码
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btn").removeAttr("disabled");//启用按钮
$("#btn").val("重新发送验证码");
} else {
curCount--;
$("#btn").val(curCount + "秒后可重新发送");
}
}
</script>
<body id="body">
<div class="container">
<div id="login">
<fieldset id="fieldset">
<div id="legend" class="">
<span style="font-size:20px">手机验证登录</span>
<span class="label label-info" id="backlogin">返回账号密码登录</span>
<hr style="border:1px solid #999;">
</div>
<form class="form-horizontal" role="form">
<div class="form-group">
<!-- 手机号 -->
<label class="col-sm-2 control-label">手机号</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="phone" name="phone" placeholder="请输入您的手机号" required/>
<span class="label label-danger" id="tishi" name="tishi"></span>
</div>
<br><br><br><br>
<!-- 验证码 -->
<div style="position:absolute;left:48%;bottom:70%">
<input class="btn btn-info" id="btn" name="btn" value="点击发送验证码" onclick="sendMessage()" style="width: 150px;"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="code" class="form-control" id="code" name="code" placeholder="验证码" required>
<span class="label label-danger" id="yanzm" name="yanzm"></span>
</div>
</div>
<br><br><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-success" id="lo">登录</button>
<a href="/user/phoneregister" class="btn btn-danger">手机注册</a>
</div>
</div>
</form>
<div class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert">
×
</a>
还未注册?点击手机注册完成登录
</div>
</fieldset>
</div>
</div>
</body>
<script type="text/javascript">
var sms = "";
$("#btn").click(function() {
var phone = $("#phone").val();
if ((phone != "")&&(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
$.ajax({
url : "/user/sendSMS", //发送请求
type : "post",
data : {
"phone" : phone
},
success : function(result) {
sms = result;
}
});
} else if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone)) && (phone != "")){
alert("请正确的手机号!");
return false;
} else{
alert("请输入手机号");
return false;
}
});
$("#lo").click(function() {
var code = $("#code").val();
if (code == "") {
$("#yanzm").html("请输入验证码");
return false;
} else {
if (sms == code) {
window.location.href = "/user/success";
} else {
("#yanzm").html("验证码有误,请重新输入");
return false;
};
};
});
$("#backlogin").click(function () {
window.location.href = "/user/login";
})
</script>
<!-- 用户判断 -->
<script>
$(function(){
$("#phone").blur(function(){
$.ajax({
url:"/user/checkCode",
type:"post",
data:{
"usercode":$("#phone").val()
},
dataType:"json",
success:function(data){
if(data.msg=="true"){
$("#tishi").html("");
$("#btn").removeAttr("disabled");
}else{
if ($("#phone").val()=="") {
$("#tishi").html("");
return false;
$("#btn").attr("disabled", "true");
}else {
$("#tishi").html("该账号还未注册!请先注册!");
return false;
$("#btn").attr("disabled", "true");
}
}
},
error:function(){
alert("验证出现错误!");
return false;
}
});
});
});
</script>
</html>
phoneregister.jsp (手机短信验证注册页面)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>手机登录</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<link rel="stylesheet" href="../../static/css/style.css" />
<link rel="stylesheet" href="../../static/css/bootstrap.min.css" />
<link rel="stylesheet" href="../../static/css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="../../static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../static/js/bootstrap.min.js"></script>
</head>
<script type="text/javascript">
$(function () {
$("#OKreg").hide();
$("#codeinfo").hide();
});
var InterValObj; //timer变量,控制时间
var count = 30; //间隔函数,1秒执行
var curCount;//当前剩余秒数
function sendMessage() {
curCount = count;
$("#btn").attr("disabled", "true");
$("#btn").val(curCount + "秒后可重新发送");
InterValObj = window.setInterval(SetRemainTime, 1000);
//启动计时器,1秒执行一次请求,发送验证码
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btn").removeAttr("disabled");//启用按钮
$("#btn").val("重新发送验证码");
} else {
curCount--;
$("#btn").val(curCount + "秒后可重新发送");
}
}
</script>
<body id="body">
<div class="container">
<div id="login">
<fieldset id="fieldset">
<div id="legend" class="">
<span style="font-size:20px">手机注册</span>
<hr style="border:1px solid #999;">
</div>
<form class="form-horizontal" role="form">
<div class="form-group">
<!-- 手机号 -->
<label class="col-sm-2 control-label">手机号</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="phone" name="phone" placeholder="请输入您的手机号" required/>
<span class="label label-danger" id="tishi" name="tishi"></span>
</div>
<br><br><br><br>
<!-- 验证码 -->
<div style="position:absolute;left:48%;bottom:70%">
<input class="btn btn-info" id="btn" name="btn" value="点击发送验证码" onclick="sendMessage()" style="width: 150px;"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="code" class="form-control" id="code" name="code" placeholder="验证码" required>
<span class="label label-danger" id="yanzm" name="yanzm"></span>
</div>
</div>
<br>
<div id="codeinfo" class="alert alert-success">
<a href="#" class="close" data-dismiss="alert">×</a>
<strong>验证成功!</strong>请输入<strong>密码</strong>完成注册。
</div>
<!-- 密码 -->
<div id="pwddiv" hidden="hidden">
<div class="form-group">
<label class="col-sm-2 control-label">密码</label>
<div class="col-sm-5">
<input type="password" class="form-control" id="phonepwd" name="phonepwd" placeholder="请输入密码"/>
</div>
</div>
<div class="form-group" style="position:relative;right: 20px;">
<label class="col-sm-2 control-label" style="width: 100px;">确认密码</label>
<div class="col-sm-5">
<input type="password" class="form-control" id="phonepwdreq" name="phonepwdreq" placeholder="请输入确认密码"/>
<span class="label label-danger" id="phonepwdreqinfo" name="phonepwdreqinfo"></span>
</div>
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-success" id="lo">点击验证</button>
<button type="button" class="btn btn-success" id="OKreg">完成注册</button>
<button type="button" class="btn btn-info" id="backlogin2">返回首页</button>
</div>
</div>
</form>
<div class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert">
×
</a>
请使用本人常用手机号注册哦~
</div>
</fieldset>
</div>
</div>
</body>
<script type="text/javascript">
var sms = "";
$("#btn").click(function() {
var phone = $("#phone").val();
if ((phone != "")&&(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
$.ajax({
url : "/user/sendSMS", //发送请求
type : "post",
data : {
"phone" : phone
},
success : function(result) {
sms = result;
}
});
} else if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone)) && (phone != "")){
alert("请正确的手机号!");
return false;
} else{
alert("请输入手机号");
return false;
}
});
$("#lo").click(function() {
var code = $("#code").val();
if (code == "") {
$("#yanzm").html("请输入验证码");
return false;
} else {
if (sms == code) {
$("#codeinfo").show();
$("#pwddiv").show();
$("#OKreg").show();
$("#lo").hide();
$("#yanzm").html("");
} else {
$("#yanzm").html("验证码有误,请重新输入");
return false;
};
};
});
$("#backlogin2").click(function () {
window.location.href = "/user/login";
})
$("#OKreg").click(function () {
$.ajax({
type: "post",
url: "/user/registerPhone",
data: {
usercode: $("#phone").val(),
userpwd: $("#phonepwdreq").val(),
},
dataType: "JSON",
async: false,
success: function (data) {
if (data == 1) {
alert("注册成功")
window.location.href = "/user/login";
} else {
alert("注册失败");
indow.location.href = "/user/phoneregister";
}
},
error: function () {
alert("提交失败");
}
});
})
</script>
<!-- 用户判断 -->
<script>
$(function(){
$("#phone").blur(function(){
$.ajax({
url:"/user/checkCode",
type:"post",
data:{
"usercode":$("#phone").val()
},
dataType:"json",
success:function(data){
if(data.msg=="true"){
$("#tishi").html("该账号已注册!请使用短信验证登录!");
$("#btn").attr("disabled", "true");
return false;
}else{
if ($("#phone").val()=="") {
$("#tishi").html("");
$("#btn").attr("disabled", "true");
return false;
}else {
$("#tishi").html("");
$("#btn").removeAttr("disabled");
return true;
}
}
},
error:function(){
$("#tishi").html("验证出现错误!");
return false;
}
});
});
<!-- 密码校验 -->
$("#phonepwdreq").blur(function () {
if ($("#phonepwd").val()!=$("#phonepwdreq").val()) {
$("#phonepwdreqinfo").html("密码不一致!请重新输入!");
return false;
}else {
$("#phonepwdreqinfo").html("");
return true;
}
})
});
</script>
</html>
updtepwd.jsp (手机短信验证修改密码,这个页面也包含根据账号密码修改密码)
<%--
Created by IntelliJ IDEA.
User: 吾有所念人
Date: 2019/11/28
Time: 9:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link rel="stylesheet" href="../../static/css/bootstrap.min.css" />
<link rel="stylesheet" href="../../static/css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="../../static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../static/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="../../static/css/login.css" />
<meta charset="utf-8" />
<title>登录</title>
<script src="../../static/js/jquery-2.2.4.min.js"></script>
<script>
$(function () {
$("#pwdtijiao").hide();
$("#codeinfo").hide();
$("#pwdtijiaophone").hide();
});
$(document).ready(function() {
$(".form").slideDown(500);
$("#landing").addClass("border-btn");
$("#registered").click(function() {
$("#landing").removeClass("border-btn");
$("#landing-content").hide(500);
$(this).addClass("border-btn");
$("#registered-content").show(500);
})
$("#landing").click(function() {
$("#registered").removeClass("border-btn");
$("#registered-content").hide(500);
$(this).addClass("border-btn");
$("#landing-content").show(500);
})
});
var InterValObj; //timer变量,控制时间
var count = 30; //间隔函数,1秒执行
var curCount;//当前剩余秒数
function sendMessage() {
curCount = count;
$("#btn").attr("disabled", "true");
$("#btn").val(curCount + "秒后可重新发送");
InterValObj = window.setInterval(SetRemainTime, 1000);
//启动计时器,1秒执行一次请求,发送验证码
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btn").removeAttr("disabled");//启用按钮
$("#btn").val("重新发送验证码");
} else {
curCount--;
$("#btn").val(curCount + "秒后可重新发送");
}
}
</script>
<!-- 用户判断 -->
<script>
$(function(){
$("#userphone").blur(function(){
$.ajax({
url:"/user/checkCode",
type:"post",
data:{
"usercode":$("#userphone").val()
},
dataType:"json",
success:function(data){
if(data.msg=="true"){
$("#phonetishi").html("");
$("#btn").removeAttr("disabled");
}else{
if ($("#userphone").val()=="") {
$("#phonetishi").html("");
return false;
$("#btn").attr("disabled", "true");
}else {
$("#phonetishi").html("该账号还未注册!请先注册!");
return false;
$("#btn").attr("disabled", "true");
}
}
},
error:function(){
alert("验证出现错误!");
return false;
}
});
});
});
</script>
</head>
<body style="background: url(../../static/img/bj1.jpg); background-size:cover;">
<div class="form" style="background-color:rgba(255,255,255,0.9);">
<form>
<div id="landing">账号密码修改</div>
<div id="registered">手机验证修改</div>
<div class="fix"></div>
<div id="landing-content" style="position: relative;top: 60px;">
<div class="inp"><input type="text" name="usercode" id="usercode" placeholder="用户账号" />
<span class="label label-danger" id="tishi" name="tishi" style="color:white;position: relative;top: 6px;"></span>
</div>
<div class="inp"><input type="password" name="oldpwd" id="oldpwd" placeholder="原密码" />
<span class="label label-success" id="codeinfo" name="codeinfo" style="color:white;position: relative;top: 6px;"></span>
</div>
<div id="updpwdshow" hidden="hidden"><%--hidden="hidden"--%>
<div class="inp"><input type="password" name="newpwd" id="newpwd" placeholder="新密码" /></div>
<div class="inp"><input type="password" name="reqnewpwd" id="reqnewpwd" placeholder="确认新密码" /></div>
</div>
<%--<input class="login" type="submit" value="登录">--%>
<button type="button" class="btn btn-success" id="login">验证</button>
<button type="button" class="btn btn-success" id="pwdtijiao" name="pwdtijiao">提交</button>
<br><br>
<button type="button" class="btn btn-primary" id="pwdbacklogin">返回首页</button>
</div>
</form>
<form>
<div id="registered-content">
<div class="inp"><input type="text" name="userphone" id="userphone" placeholder="请输入手机号" />
<span class="label label-danger" id="phonetishi" name="phonetishi" style="color:white;position: relative;top: 6px;"></span>
</div>
<div class="inp">
<input type="text" name="phonecode" id="phonecode" placeholder="验证码" />
<span class="label label-danger" id="yanzm" name="yanzm" style="color:white;position: relative;top: 6px;"></span>
<!-- 验证码 -->
<input class="btn btn-info" id="btn" name="btn" value="点击发送验证码" onclick="sendMessage()" style="width: 150px;position: relative;left: 25px;top: 20px;"/>
<span class="label label-success" id="codeyz" name="codeyz" style="color:white;position: relative;top: 30px;"></span>
</div>
<br><br>
<button type="button" class="btn btn-success" id="phonecodeyz">验证</button>
<div id="updpwdshowphone" hidden="hidden"><%--hidden="hidden"--%>
<div class="inpphone"><input type="password" name="newpwdphone" id="newpwdphone" placeholder="新密码" /></div>
<br>
<div class="inpphone"><input type="password" name="reqnewpwdphone" id="reqnewpwdphone" placeholder="确认新密码" /></div>
</div>
<br>
<%--<input class="login" type="submit" value="登录">--%>
<button type="button" class="btn btn-success" id="pwdtijiaophone" name="pwdtijiaophone" >提交</button>
<br>
<button type="button" class="btn btn-primary" id="pwdbackphone">返回首页</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var sms = "";
$("#btn").click(function() {
var phone = $("#userphone").val();
if ((phone != "")&&(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
$.ajax({
url : "/user/sendSMS", //发送请求
type : "post",
data : {
"phone" : phone
},
success : function(result) {
sms = result;
}
});
} else if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone)) && (phone != "")){
alert("请正确的手机号!");
return false;
} else{
alert("请输入手机号");
return false;
}
});
$("#phonecodeyz").click(function() {
var code = $("#phonecode").val();
if (code == "") {
$("#yanzm").html("请输入验证码");
return false;
} else {
if (sms == code) {
$("#yanzm").hide();
$("#phonecodeyz").hide();
$("#pwdtijiaophone").show();
$("#updpwdshowphone").show();
$("#codeyz").show();
$("#codeyz").html("验证成功!请输入新密码完成修改")
} else {
$("#yanzm").html("验证码有误,请重新输入");
return false;
};
};
});
$("#pwdtijiaophone").click(function () {
$.ajax({
type: "post",
url: "/user/modifyPwd",
data: {
usercode: $("#userphone").val(),
userpwd: $("#reqnewpwdphone").val(),
},
dataType: "JSON",
async: false,
success: function (data) {
if (data == "1") {
alert("修改成功")
window.location.href = "/user/login";
} else {
alert("修改失败");
window.location.href = "/user/updatepwd";
}
},
error: function () {
alert("提交失败");
}
});
})
</script>
<%--账号密码修改--%>
<script>
$("#pwdbacklogin").click(function() {
window.location.href="/user/login"
});
$("#pwdbackphone").click(function() {
window.location.href="/user/login"
});
<!-- 用户判断 -->
$(function(){
$("#usercode").blur(function(){
$.ajax({
url:"/user/checkCode",
type:"post",
data:{
"usercode":$("#usercode").val()
},
dataType:"json",
success:function(data){
if(data.msg=="true"){
$("#tishi").html("");
}else{
if ($("#usercode").val()=="") {
$("#tishi").html("");
return false;
}else {
$("#tishi").html("该账号不存在");
return false;
}
}
},
error:function(){
alert("验证出现错误!");
return false;
}
});
});
});
<!-- 账号密码判断 -->
$("#login").click(function () {
$.ajax({
type: "post",
url: "/user/checkUserandPwd",
data: {
usercode: $("#usercode").val(),
userpwd: $("#oldpwd").val(),
},
dataType: "JSON",
async: false,
success: function (data) {
if (data == 1) {
$("#pwdtijiao").show();
$("#updpwdshow").show();
$("#codeinfo").show();
$("#codeinfo").html("验证成功!请输入新密码完成修改")
$("#login").hide();
} else {
alert("密码错误,请重试!");
return false;
}
},
error: function () {
alert("提交失败");
return false;
}
});
});
<!-- 账号密码修改 -->
$("#pwdtijiao").click(function () {
$.ajax({
type: "post",
url: "/user/modifyPwd",
data: {
usercode: $("#usercode").val(),
userpwd: $("#reqnewpwd").val(),
},
dataType: "JSON",
async: false,
success: function (data) {
if (data == "1") {
alert("修改成功")
window.location.href = "/user/login";
} else {
alert("修改失败");
window.location.href = "/user/updatepwd";
}
},
error: function () {
alert("提交失败");
}
});
})
</script>
</html>
JSP的页面基本就是这些,无关紧要的我没贴出来。
新建一个sendSMS.java 最好根据官方API来创建
//用户发送验证短信
@RequestMapping("/sendSMS")
public void sendSMS(HttpServletRequest req, HttpServletResponse resp)throws Exception {
String phone=req.getParameter("phone");
//根据获取到的手机号发送验证码
String code = GetMessageCode.getCode(phone);
System.out.println("这是code:"+code);
resp.getWriter().print(code);
}
在util包中创建一个工具类 GetMessageCode.java
package com.sxh.util;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.sxh.util.Config;
import com.sxh.util.HttpUtil;
public class GetMessageCode {
private static String operation = "/distributor/sendSMS";//对应的API地址
private static String accountSid = Config.ACCOUNT_SID;
private static String to = ""; //前台传入要登录的手机号
private static String rod = smsCode(); //生成一个随机验证码
private static String smsContent = "【咕噜咕噜虎】亲爱的用户,您的短信验证码为:"+rod+",2分钟内有效,若非本人操作请忽略。";
//创建验证码
public static String smsCode(){
String random=(int)((Math.random()*9+1)*100000)+"";
System.out.println("random验证码:"+random);
return random;
}
//根据相应的手机号发送验证码
public static String getCode(String phone){
String tmpSmsContent = null;
try{
tmpSmsContent = URLEncoder.encode(smsContent, "UTF-8");
}catch(Exception e){
e.getMessage();
}
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + phone + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
// 提交请求
String result = HttpUtil.post(url, body);
//(换行符) 剔除了平台无关性
System.out.println("这是result:" + System.lineSeparator() + result);
System.out.println(result.getClass());
//字符串转json对象
JSONObject jsonObject = JSONObject.parseObject(result);
String respCode = jsonObject.getString("respCode");
System.out.println("这是respCode:"+respCode);
//反馈-00000状态码标识请求成功,
String defaultRespCode="00000";
if(defaultRespCode.equals(respCode)){
return rod;
}else{
return defaultRespCode;
}
}
}
提示一下:在GetMessageCode类中,把smsContent改为你自己在平台上面建立的模板的样式,这里必须一致。
再次创建Config类
package com.sxh.util;
public class Config {
/**
* url前半部分
*/
public static final String BASE_URL = "https://openapi.miaodiyun.com";
/**
* 开发者注册后系统自动生成的账号,可在官网登录后查看-修改为自己的。
*/
public static final String ACCOUNT_SID = "2xxxxxxxxxxxxxxxxxxxxxxxxxx8";
/**
* 开发者注册后系统自动生成的TOKEN,可在官网登录后查看-修改为自己的。
*/
public static final String AUTH_TOKEN = "cxxxxxxxxxxxxxxxxxxxxxxxxxxx9";
/**
* 响应数据类型, JSON或XML
*/
public static final String RESP_DATA_TYPE = "json";
}
新建HttpUtil请求类,也是在工具包中创建
package com.sxh.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.codec.digest.DigestUtils;
public class HttpUtil {
/**
* 构造通用参数timestamp、sig和respDataType
*
* @return
*/
public static String createCommonParam()
{
// 时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
// 签名
String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);
return "×tamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
}
/**
* post请求
* @return
* @throws IOException
*/
public static String post(String url, String body)
{
//url功能和操作
System.out.println("url:" + System.lineSeparator() + url);
//body要post的数据
System.out.println("body:" + System.lineSeparator() + body);
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置连接参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 提交数据
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 读取返回数据
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 读第一行不加换行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
/**
* 回调测试工具方法
*
* @param url
* @return
*/
public static String postHuiDiao(String url, String body)
{
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置连接参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
// 提交数据
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 读取返回数据
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 读第一行不加换行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
在浏览器输入http://localhost:8080/user/login 这个一般会springMVC都知道需要在controller配置注解访问。
我们点击手机登录
在input输入手机号,我对手机号做了判断,要是数据库有就不提示异常,没有则提醒,且“点击发送验证码”按钮被禁用。
很简单鼠标离开事件,鼠标离开这个框就请求controller的方法。这个可以自己尝试写一下。
然后发送验证码,这时候控制台也已经打印出来了
再看一下手机
没毛病。
验证码正确的话 我们就可以直接登录上了。(简单做个success.jsp测试一下)
跟登录大同小异,只要验证码对了才显示密码栏:
对了,要是手机号注册过了就不能操作了哦
否则就可以注册
错误提示:
好了,以上就是短信验证的一系列功能,代码都已经贴出来了。完全可以实现发送短信功能。
其他的功能小伙伴们可以自己尝试编写,请求方法我已经全部在JSP页面写出来了,小伙伴可以参考一下。本人才开通博客,欢迎小伙伴关注哦~