Spring MVC短信验证码的实现

2016年04月22日 Spring 评论 1 条 阅读 5,841 views 次

在外部网站中短信的验证很有必要,比如在实现注册、验证用户信息等的情况下。在SpringMVC中的实现如下:

短信接口

短信接口,有些企业会购买的有移动的短信平台接口。如果是个人或者是小企业可以使用一些云服务的。比如百度的API Store上面的。

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

当然短信接口肯定都是要付费的,而且是基于模板的,具体的使用说明可以看这个网址里面的使用说明。

前端界面

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

sms-captcha

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

$("#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改成自己的。

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做一下表单的验证,验证一下验证码是否正确:

@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";
    }
}
用户头像

1 条留言  访客:1 条  博主:0 条

  1. 这几个常量怎么设置的初始值?

给我留言取消回复

您必须 登录 才能发表留言!

Copyright © IT人生录 保留所有权利.   主题设计 知更鸟 滇ICP备16001547号

用户登录

分享到: