用户登录到页面 - 输入手机号- 点击获取验证码按钮-后台生成6位随机数 - 通过第三方平台发送到手机 - 并把随机验证码放到session - 用户输入验证码 - 后台匹配手机号与验证码 - 120秒后自动清空session中的验证码(用java定时器)
前台没必要展示了.
controller:
@RequestMapping(value="/provePhone",method=RequestMethod.POST)
public Object provePhone(Model model,String phone,HttpSession session) throws HttpException, IOException{
String msg="手机号码格式错误!";
if(phone.length()!=11){
model.addAttribute("msg", msg);
model.addAttribute("phone", phone);
return "login";
}else{
//发送随机6位验证码到手机
int phoneCode=SendPhoneCode.phoneCodeStart(phone);
//放入session
session.setAttribute("phone", phone);
session.setAttribute("phoneCode", String.valueOf(phoneCode));
//120秒后清除session中的验证码
SendPhoneCode.removeSessionPhoneCode(session);
msg="发送成功!请填写验证码!";
model.addAttribute("phong", phone);
model.addAttribute("msg", msg);
}
return "login";
}
发送短信随机数和定时器写一个类里了.懒得分开了
public class SendPhoneCode {
public static int phoneCodeStart(String phone) throws HttpException, IOException {
Random r=new Random();
int i=r.nextInt(899999);
int a=i+100000;
String phoneCode="验证码:"+String.valueOf(a)+ "验证码120秒有效";
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
NameValuePair[] data = { new NameValuePair("Uid", "bikepark"), new NameValuePair("Key", "xxxxxxxxxxxxxxxxxxx"),
new NameValuePair("smsMob", phone), new NameValuePair("smsText", phoneCode) };
post.setRequestBody(data);
client.executeMethod(post);
Header[] headers = post.getResponseHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:" + statusCode);
for (Header h : headers) {
System.out.println(h.toString());
}
String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
System.out.println(result); // 打印返回消息状态
post.releaseConnection();
return a;
}
/**
* 定时器 120秒后清除session中的验证码
* @param session
*/
public static void removeSessionPhoneCode(HttpSession session){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
session.removeAttribute("phoneCode");
}
}, 120000);// 设定指定的时间time,1秒为1000毫秒
}
}
再对手机验证码验证是否匹配
@RequestMapping("/phoneCode")
public Object phoneCode(HttpSession session,String phone,String phoneCode,Model model){
String msg="";
if(session.getAttribute("phone").equals(phone)&&session.getAttribute("phoneCode").equals(phoneCode)){
msg="验证通过!";
model.addAttribute("phone", phone);
model.addAttribute("msg",msg );
return "login";
}else{
msg="验证未通过!";
model.addAttribute("phone", phone);
model.addAttribute("msg",msg );
return "login";
}
}
注意:两次请求的方式必须都是"POST",否则第二次验证的请求会创建一个新session就匹配不到之前的随机数了.
对了,第三方短信平台用的"中国网建".