前面文章中分享了java发送验证码短信的demo(https://blog.youkuaiyun.com/zuoliangzhu/article/details/89790589),对于初级开发者来说还是有一定难度,为此我又完善了一下demo,增加了对于验证码的管理,包括存储到session中、校验验证码功能,都封装到了SessionUtil.java中。
public class SessionUtil {
/**
* 保存验证码信息
* @param session
* @param mobile 手机号码
* @param code 验证码
* @param expire 有效时间,单位(秒)
*/
public static void save(
HttpSession session,
String mobile,
String code,
int expire){
session.setAttribute("zhenzisms_mobile", mobile);
session.setAttribute("zhenzisms_code", code);
session.setAttribute("zhenzisms_createTime", System.currentTimeMillis());
session.setAttribute("zhenzisms_expire", expire);
}
/**
* 校验验证码
* @param session
* @param mobile 手机号码
* @param code 验证码
* @param expire 有效时间,单位(秒)
*/
public static String validate(
HttpSession session,
String mobile,
String code){
String sessionMobile = blank(session.getAttribute("zhenzisms_mobile"));
String sessionCode = blank(session.getAttribute("zhenzisms_code"));
String createTime = blank(session.getAttribute("zhenzisms_createTime"));
String expire = blank(session.getAttribute("zhenzisms_expire"));
if(sessionMobile.equals(""))
return "未生成验证码";
if(!sessionMobile.equals(mobile)){
return "手机号错误";
}
if(!sessionCode.equals(code)){
return "验证码错误";
}
if((System.currentTimeMillis() - Long.parseLong(createTime)) > 1000 * Integer.parseInt(expire)){
return "验证码已过期";
}
save(session, "", "", 0);
return "";
}
private static String blank(Object s){
if(s == null)
return "";
return s.toString();
}
}
当你调用短信平台接口发送短信后,就可以直接使用上面的方法了:
//生成6位验证码
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
System.out.print("验证码: "+verifyCode);
//发送短信
ZhenziSmsClient client = new ZhenziSmsClient(Config.apiUrl, Config.appId, Config.appSecret);
Map<String, Object> params = new HashMap<String, Object>();
params.put("number", number);
params.put("templateId", templateId);
String[] templateParams = {verifyCode, "5分钟内有效"};
params.put("templateParams", templateParams);
String result = client.send(params);
json = JSONObject.parseObject(result);
if(json.getIntValue("code") != 0){//发送短信失败
renderData(response, "获取失败:"+json.getString("data"));
return;
}
//将验证码存到session中,同时存入创建时间
HttpSession session = request.getSession();
SessionUtil.save(session, number, verifyCode, 5 * 60);
校验验证码,包括核对手机号、验证码是否正确,以及验证码有效期的管理:
String number = request.getParameter("number");
String verifyCode = request.getParameter("verifyCode");
String error = SessionUtil.validate(request.getSession(), number, verifyCode);
if(!error.equals("")){
renderData(response, error);
return ;
}
//其他业务代码
renderData(response, "success");
完整demo免费下载:http://smsow.zhenzikj.com/doc/sdk.html
或者直接下载: http://smsow.zhenzikj.com/demo/download.html?fileName=zhenzisms_java_demo
demo项目说明:
浏览器直接输入http://ip:端口/zhenzisms_demo/index.jsp 进入demo导航:
通用短信发送示例对应common.jsp, 验证码短信发送对应code.jsp