Spring MVC短信验证码的实现

在外部网站中短信的验证颇有必要,好比在实现注册、验证用户信息等的状况下。在SpringMVC中的实现以下:html

短信接口

短信接口,有些企业会购买的有移动的短信平台接口。若是是我的或者是小企业可使用一些云服务的。好比百度的API Store上面的。前端

我使用的是:http://apistore.baidu.com/apiworks/servicedetail/1018.htmlajax

固然短信接口确定都是要付费的,并且是基于模板的,具体的使用说明能够看这个网址里面的使用说明。spring

前端界面

前端的界面,可能以下,点击获取验证码,而后按钮变为灰色而且倒计时。(手机号是个人~~)后端

sms-captcha

HTML代码就不写了,JS以下:vailidationCode是获取验证码按钮的ID。phone是手机号码的ID,手机号码只是简单的验证了,若是是要更精确,使用正则,其中的url的sendSms是后台的springMVC的路径。api

$("#validationCode").click(function(){
    var phone = $("#phone").val();
    if($("#phone").val() && $("#phone").val().length == 11){
        $.ajax({
            cache : false,
            url : "sendSms",
            data : {phone : phone}
        });
        updateButtonStatus();
    }else {
        alert("请输入合法的手机号");
    }
});

var countdown=60;
function updateButtonStatus(){
    var phone = $("#validationCode");
    if (countdown == 0) {
        phone.attr("disabled","false");
        phone.val("免费获取验证码");
        countdown = 60;
        return;
    } else {
        phone.attr("disabled","true");
        phone.val("从新发送(" + countdown + ")");
        countdown--;
    }
    setTimeout(function() {
                updateButtonStatus() }
            ,1000)
}

后端代码

@RequestMapping(value = "/sendSms")
@ResponseBody
public String sendSMS(@RequestParam("phone") String phone, HttpServletRequest request){
    StringBuilder code = new StringBuilder();
    Random random = new Random();
    // 生成6位验证码
    for (int i = 0; i < 6; i++) {
        code.append(String.valueOf(random.nextInt(10)));
    }
    HttpSession session = request.getSession();
    session.setAttribute(VALIDATE_PHONE, phone);
    session.setAttribute(VALIDATE_PHONE_CODE, code.toString());
    session.setAttribute(SEND_CODE_TIME, new Date().getTime());
    String smsText = "您的验证码是:"+code;
    SMSUtil.send(phone,smsText);
    return "success";
}

其中的SMSUtil是封装的上面的短信接口的发送类。参考以下,其中的API_KEY改为本身的。spring-mvc

public class SMSUtil {

    static String httpUrl = "http://apis.baidu.com/kingtto_media/106sms/106sms";
    final static String API_KEY = "xxxx";

    public static String send(String phone,String content) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        try {
            String httpArg = "mobile="+phone+"&content="+URLEncoder.encode(content,"UTF-8")+"&tag=2";
            httpUrl = httpUrl + "?" + httpArg ;
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",API_KEY);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

前台的表单提交前还须要使用ajax作一下表单的验证,验证一下验证码是否正确:session

@RequestMapping("/validate")
@ResponseBody
protected String validate(HttpServletRequest request,@RequestParam("phone") String inputPhone,@RequestParam ("code") String inputCode){
    HttpSession session = request.getSession();
    String code = (String) session.getAttribute(VALIDATE_PHONE_CODE);
    String phone = (String) session.getAttribute(VALIDATE_PHONE);
    if(phone.equals(inputPhone) && code.equalsIgnoreCase(inputCode)){
        return "success";
    }else{
        return "failure";
    }
}
相关文章
相关标签/搜索