版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengshuoa/article/details/52230282
说是js发送验证码,其实真正实现发送短信功能的还是在服务器,js不过是触发发送功能。
大致流程如下:
1、客户端js通过发送http请求(发短信接口)到服务器,将手机号等信息传递给服务器
2、服务器收到请求后校验参数,参数正确调用第三方短信接口,并将随机产生的验证码保存在服务器(通常是数据库或者缓存),参数错误,将错误信息返回给客户端
3、客户端收到服务器的返回,如果调用成功,开始倒计时同时等待用户输入收到的验证码,如果调用失败,将失败信息提示给用户。
4、用户输入验证码后,将验证码和手机号等信息发送到服务器校验
5、服务器收到校验请求后,对手机号和验证码用验证,将结果返回给客户端
6、客户端收到验证结果后,提示用户或者开始其他业务
本示例采用js+servlet,注意要在web.xml中配置<servlet>
短信接口采用 sms短信通 附上网址:http://www.smschinese.cn/api.shtml
jsp页面代码:
后台代码
获取验证码发送短信:
验证码验证:
大致流程如下:
1、客户端js通过发送http请求(发短信接口)到服务器,将手机号等信息传递给服务器
2、服务器收到请求后校验参数,参数正确调用第三方短信接口,并将随机产生的验证码保存在服务器(通常是数据库或者缓存),参数错误,将错误信息返回给客户端
3、客户端收到服务器的返回,如果调用成功,开始倒计时同时等待用户输入收到的验证码,如果调用失败,将失败信息提示给用户。
4、用户输入验证码后,将验证码和手机号等信息发送到服务器校验
5、服务器收到校验请求后,对手机号和验证码用验证,将结果返回给客户端
6、客户端收到验证结果后,提示用户或者开始其他业务
本示例采用js+servlet,注意要在web.xml中配置<servlet>
短信接口采用 sms短信通 附上网址:http://www.smschinese.cn/api.shtml
jsp页面代码:
<html>
<head>
<base href="<%=basePath%>">
<title>message</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#getCode").removeAttr("disabled");
//发送验证码
$("#getCode").click(function(){
$.ajax({
url:"messageServlet",
data:{
"phone":$("#phone").val()
},
type:"post",
async:false,
dataType:"text",
success : function(data) {
if(data=='true'){
alert("验证码发送成功,收到后请输入验证码");
time(this);
} else {
alert("验证码发送失败");
}
},
error : function() {
alert("error");
}
});
});
//验证
$("#validate").click(function(){
$.ajax({
url:"codeServlet",
data:{
"code":$("#code").val()
},
type:"post",
async:false,
dataType:"text",
success : function(data) {
if(data=='true'){
alert("恭喜您,验证成功");
} else {
alert("验证失败");
}
},
error : function() {
alert("error");
}
});
});
})
//验证码倒计时
var wait = 60;
function time(obj) {
if(wait==0) {
$("#getCode").removeAttr("disabled");
$("#getCode").val("获取验证码");
wait = 60;
}else {
$("#getCode").attr("disabled","true");
$("#getCode").val(wait+"秒后重试");
wait--;
setTimeout(function() { //倒计时方法
time(obj);
},1000); //间隔为1s
}
}
</script>
</head>
<body>
<input type="text" id="phone" placeholder="请输入手机号码"><input id="getCode" type="button" value="获取验证码"><br>
<input type="text" id="code" placeholder="6位验证码"><input id="validate" type="button" value="验证">
</body>
</html>
后台代码
获取验证码发送短信:
<span id="transmark"></span>
package message;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class messageServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String phone=request.getParameter("phone");
response.setCharacterEncoding("UTF-8");
//获取验证码
String code = getCode(request);
//发送短信
sendMsg(phone,code);
response.getWriter().write("true");
response.flushBuffer();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
//发送短信
private void sendMsg(String phone,String code) throws HttpException, IOException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn/");
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
NameValuePair[] data ={
new NameValuePair("Uid", "xxx"),// 注册的用户名
new NameValuePair("Key", "xxx"),// 注册成功后,登录网站后得到的密钥
new NameValuePair("smsMob",phone),// 手机号码
new NameValuePair("smsText","验证码:"+code)};// 短信内容
post.setRequestBody(data);
client.executeMethod(post);
Header[] headers = post.getResponseHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:"+statusCode);
for(Header h : headers)
{
System.out.println("-----"+h.toString());
}
String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
System.out.println(result); //打印返回消息状态
post.releaseConnection();
}
//获取验证码
private String getCode(HttpServletRequest request) {
Random rand =new Random();
String code = "";
for(int i=0;i<4;i++) {
code += rand.nextInt(10);
}
request.getSession().setAttribute("code",code);
return code;
}
}
验证码验证:
package message;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class codeServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
response.setCharacterEncoding("UTF-8");
if(request.getSession().getAttribute("code").equals(code)){
response.getWriter().write("true");
}else {
response.getWriter().write("false");
}
response.flushBuffer();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}