最近自学了短信的验证码实现。以下是自己用的一种方法实现的完整的过程。
短信验证登陆(前端+后台)
1、前端填写手机号以及点击触发,以电话号码为参数调用发送验证登录短信方法并在前端产生随机数存于Seesion 中,将手机号连同产生的随机数发送到后台操作(已经设置好缓存存放时间)
2、调用发送模板短信方法发送短信(设置好短信中验证码有效的时间)
3、点击触发登陆,调用对应验证登录函数 ,以电话号码和验证码为参数
4、校验缓存中对应保留的信息
如果一致,登陆成功;登陆不成功是返回原因(1、超时 2、验证码输入错误)实现:
我的实现是利用网易云信实现的。
1. 注册网易云信
2. 创建IM 应用
3. 一般首次注册会有免费的短信条数,不用去购买
4. 创建一个短信模板,等待审核
5. 在自己创建的IM 应用中找到 把相应的Appkey和appSecret放入到代码中
由于使用的网易云信得短信验证故无法得知他把我们获取到的验证码放置在了何处,故在这里的校验验证码我们也只能交给网易云信来判断,我们只能对写出后台代码来传送给网易云信,主要是若想真正的实现验证我们需要一个api的接口来实现。
下面是一个简单的短信验证的例子(包括了对短信获取到的验证码的验证)
1、 前端代码(html)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>短信验证码实现 手机号:验证码:
2. 前端代码(jsp+css)
/*检查手机号是否正确*/function checkNum() { if ($("#phoneNum").val() == null || $("#phoneNum").val() == "") { $("#errormessage").css({ "display" : "block", "border" : "none", "color" : "red" }); $("#errormessage").val("手机号不能为空!"); } else if (!(/^1[3|5|8|4][0-9]\d{ 4,8}$/.test($("#phoneNum").val()))) { /* 正则表达式判断手机号是否符合标准 */ $("#errormessage").css({ "display" : "block", "border" : "none", "color" : "red" }); $("#errormessage").val("手机号格式不对!"); } else { $("#errormessage").css({ "display" : "block", "border" : "none", "color" : "green" }); $("#errormessage").val("√"); }}//先随机产生4位数字,保存到数据库,然后发送到手机上var number;// 倒计时var time = 61;var t;// 获取验证码$(document).ready(function() { $('#gettime').click(function() { // 先随机产生4位数字,保存到数据库,然后发送到手机上 number = Math.floor(Math.random() * 9000) + 1000; t = setInterval("gettime()", 1000); var phone = $("#phoneNum").val(); location.href="MessageSend?&phone="+$("#phoneNum").val()+"&number="+$("confirmNum").val(); alert(number+"-------"+phone); })})/*修改时间,即在时间段内没有获取到*/function gettime() { time--; if (time > 0) { $('#gettime').val(time + 's'); $('#gettime').css("color", "red"); } else { $('#gettime').val('重新获得验证码'); $('#gettime').css("color", "red"); t = clearInterval(t);/* 清楚时间重新获取 */ time = 61; }}/*将填写的数据传送到servlet中*/function logins(){ location.href="MessageCheck?&phone="+$("#phoneNum").val()+"&checknum="+$("confirmNum").val();}CSS#bodys{ margin:200px auto 0px; width:450px;}#top { height: 40px; }#top #left{ float: left; }#top #right{ float: right; }#top input{ width:200px; }#foot{ position: relative; top: 10px; }#tool{ position: relative; top: 10px; }
3.发送验证码(java)
package com.mobile; import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;@WebServlet("/MessageSend")public class MessageSend extends HttpServlet { private static final long serialVersionUID = 1L; private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";// 发送验证码的请求路径URL private static final String APP_KEY = "0b4828b25c0**************c41";// 网易云信分配的账号 private static final String APP_SECRET = "5***97";// 网易云信分配的密钥 private static final String NONCE = "123456";// 随机数 public MessageSend() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setHeader("Context-type", "text/html;Charset=utf-8"); String phone = request.getParameter("phone"); String number = request.getParameter("number"); //将数据再次返回给页面显示 request.setAttribute("phone", phone); request.setAttribute("number", number); System.out.println( "phone:---"+request.getParameter("phone")); sendMsg(phone); request.getRequestDispatcher("Phone.jsp").forward(request, response); } public static String sendMsg(String phone) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(SERVER_URL); String curTime=String.valueOf((new Date().getTime()/1000L)); String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime); //设置请求的header post.addHeader("AppKey",APP_KEY); post.addHeader("Nonce",NONCE); post.addHeader("CurTime",curTime); post.addHeader("CheckSum",checkSum); post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); //设置请求参数 ListnameValuePairs =new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("mobile",phone)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8")); //执行请求 HttpResponse response=httpclient.execute(post); String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8"); //判断是否发送成功,发送成功返回true String code= JSON.parseObject(responseEntity).getString("code"); if (code.equals("200")){ return "success"; } return "error"; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
4 验证短信验证码
com.mobile; import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; /** * Servlet implementation class MessageCheck */@WebServlet("/MessageCheck")public class MessageCheck extends HttpServlet { private static final long serialVersionUID = 1L; private static final String SERVER_URL = "https://api.netease.im/sms/verifycode.action";// 校验验证码的请求路径URL private static final String APP_KEY = "0b482******1";// 网易云信分配的账号 private static final String APP_SECRET = "5*****97";// 网易云信分配的密钥 private static final String NONCE = "123456";// 随机数 /** * @see HttpServlet#HttpServlet() */ public MessageCheck() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setHeader("Context-type", "text/html;Charset=utf-8"); String phone = request.getParameter("phone"); String checknum = request.getParameter("checknum"); checkMsg(phone,checknum); request.getRequestDispatcher("index.jsp").forward(request, response); } public static String checkMsg(String phone,String sum) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(SERVER_URL); String curTime=String.valueOf((new Date().getTime()/1000L)); String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime); //设置请求的header post.addHeader("AppKey",APP_KEY); post.addHeader("Nonce",NONCE); post.addHeader("CurTime",curTime); post.addHeader("CheckSum",checkSum); post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); //设置请求参数 ListnameValuePairs =new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("mobile",phone)); nameValuePairs.add(new BasicNameValuePair("code",sum)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8")); //执行请求 HttpResponse response=httpclient.execute(post); String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8"); //判断是否发送成功,发送成功返回true String code= JSON.parseObject(responseEntity).getString("code"); if (code.equals("200")){ return "success"; } return "error"; } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
至此便可以实现短信的验证码