手机验证码注册
注册的时候使用手机号验证码登录,使用两个form表单,之前直接通过form里面再套接一个form表单,发现提交的时候会出现问题,后面通过学习了解到jsp的一个标签,<jsp:include page=“需要显示的另一个页面地址”></jsp:include>,这样就可以通过另一个页面的form表单提交手机号码然后进行处理
手机号验证需要先在一个短信平台上面注册一个账号,我选择的是在秒嘀平台上面注册,注册以后会送十块钱免费短信体验,如果只是为了做做小的demo也完全够用了
注册以后需要创建一个短信模板
然后会生成一个开发者信息
这上面的信息在后面代码会用到
具体代码如下:
PhoneCode.jsp代码:
<title>手机验证</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" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css"/>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style type="text/css">
/* #login{ width:450px; height:100px; margin:50px auto;}*/
/*#btn{ margin-left:100px; margin-top:-25px; width: 120px;height: 25px; font-size: 11px; }
body{ background-color: #ecfcf9;}*/
.imgx > img {
width: 30px;
height: 30px;
padding-top: 2px;
}
</style>
</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秒执行一次请求后台发送验证码 TODO
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btn").removeAttr("disabled");//启用按钮
$("#btn").val("重新发送验证码");
}
else {
curCount--;
$("#btn").val(curCount + "秒后可重新发送");
}
}
</script>
<body>
<form class="form-horizontal" role="form">
<tr>
<td class="col-lg-3 col-ms-3">
<label>手机号</label>
</td>
<td class="col-lg-3 col-ms-3">
<input type="text" class="col-lg-12 col-ms-12" id="phone" name="phone" placeholder="请输入您的手机号" onfocus="hhh()" onblur="checkTel()">
</td>
<td class="col-lg-3 col-ms-3 imgx">
<img src="img/notliang.png" id="img5">
</td>
</tr>
<tr>
<td class="col-lg-3 col-ms-3">
<label>验证码</label>
</td>
<td class="col-lg-3 col-ms-3">
<input type="code" class="col-lg-12 col-ms-12" size="6" id="code" name="code" placeholder="验证码" onblur="checkCode()">
<input class="col-lg-12 col-ms-12 btn btn-default" id="btn" name="btn" width="50px" value="发送验证码" onclick="sendMessage()"/>
</td>
</tr>
</form>
</body>
<script type="text/javascript">
var sms = "";
$("#btn").click(function () {
var phone = $("#phone").val();
if (phone != "") {
$.ajax({
url: "/send",
type: "post",
data: {"phone": phone},
success: function (result) {
sms = result;
}
});
} else {
alert("请输入手机号");
return false;
}
});
function checkCode() {
var code = $("#code").val();
if (code == "") {
return false;
} else {
if (sms == code) {
return true;
} else {
return false;
}
}
}
function hhh() {
var img = document.getElementById("img5");
img.src = "img/liang.png";
}
function checkTel() {
var img = document.getElementById("img5");
var tel = document.getElementById("tel").value;
var regExp = new RegExp("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
if (regExp.test(tel)) {
img.src = "img/true.png";
return true;
} else {
img.src = "img/false.png";
return false;
}
}
</script>
</html>
index.jsp代码如下
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/myServlet">
用户名<input type="text" name="name" id="name">
密码<input type="text" name="password" id="password">
<jsp:include page="PhoneCode.jsp"></jsp:include>
</form>
</body>
</html>
后台数据处理:
send.java代码如下:
@WebServlet(value = "/send", name = "Send")
public class Send extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String phone = req.getParameter("phone");
//根据获取到的手机号发送验证码
System.out.println("执行了");
String code = GetCode.getCode(phone);
System.out.println(code);
resp.getWriter().print(code);
}
}
GetCode代码:
public class GetMessageCode {
private static final String QUERY_PATH="https://api.miaodiyun.com/20150822/industrySMS/send";
private static final String ACCOUNT_SID="开发者信息里面的SID";
private static final String AUTH_TOKEN="开发者信息里面的TOKEN";
//根据相应的手机号发送验证码
public static String getCode(String phone){
String rod=smsCode();
String timestamp=getTimestamp();
String sig=getMD5(ACCOUNT_SID,AUTH_TOKEN,timestamp);
//注意这个地方必须和新建模板的一模一样,一个标点符号都不能少
String tamp="【心灵科技】登录验证码:"+rod+",如非本人操作,请忽略此短信。";
OutputStreamWriter out=null;
BufferedReader br=null;
StringBuilder result=new StringBuilder();
try {
URL url=new URL(QUERY_PATH);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);//设置是否允许数据写入
connection.setDoOutput(true);//设置是否允许参数数据输出
connection.setConnectTimeout(5000);//设置链接响应时间
connection.setReadTimeout(10000);//设置参数读取时间
connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
//提交请求
out=new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
String args=getQueryArgs(ACCOUNT_SID, tamp, phone, timestamp, sig, "JSON");
out.write(args);
out.flush();
//读取返回参数
br=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String temp="";
while((temp=br.readLine())!=null){
result.append(temp);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(rod);
JSONObject json=new JSONObject(result.toString());//停止执行?
System.out.println("json执行了");
String respCode=json.getString("respCode");
String defaultRespCode="000000";
if(defaultRespCode.equals(respCode)){
System.out.println("也执行了");
return defaultRespCode;
}else{
System.out.println("rod执行了");
return rod;
}
}
//定义一个请求参数拼接方法
public static String getQueryArgs(String accountSid,String smsContent,String to,String timestamp,String sig,String respDataType){
return "accountSid="+accountSid+"&smsContent="+smsContent+"&to="+to+"×tamp="+timestamp+"&sig="+sig+"&respDataType="+respDataType;
}
//获取时间戳
public static String getTimestamp(){
return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
}
//sing签名
public static String getMD5(String sid,String token,String timestamp){
StringBuilder result=new StringBuilder();
String source=sid+token+timestamp;
//获取某个类的实例
try {
MessageDigest digest=MessageDigest.getInstance("MD5");
//要进行加密的东西
byte[] bytes=digest.digest(source.getBytes());
for(byte b:bytes){
String hex=Integer.toHexString(b&0xff);
if(hex.length()==1){
result.append("0"+hex);
}else{
result.append(hex);
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result.toString();
}
//创建验证码
public static String smsCode(){
String random=(int)((Math.random()*9+1)*100000)+"";
return random;
}
}
实现这个还需要三个包
可以通过http://maven.ibiblio.org/maven/找到对应jar包进行下载
如果还有什么问题可以在下面留言,谢谢支持