⽤户登录到页⾯ - 输⼊⼿机号- 点击获取验证码按钮-后台⽣成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中的验证码
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 Int(899999);
int a=i+100000;
String phoneCode="验证码:"+String.valueOf(a)+ "验证码120秒有效";
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("gbk.api.smschinese");
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);
Header[] headers = ResponseHeaders();
int statusCode = StatusCode();
System.out.println("statusCode:" + statusCode);
for (Header h : headers) {
System.out.String());
}
String result = new ResponseBodyAsString().getBytes("gbk"));
System.out.println(result); // 打印返回消息状态
return a;验证码自动输入
}
/**
* 定时器 120秒后清除session中的验证码
* @param session
*/
public static void removeSessionPhoneCode(HttpSession session){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
}
}, 120000);// 设定指定的时间time,1秒为1000毫秒
}
}
再对⼿机验证码验证是否匹配
@RequestMapping("/phoneCode")
public Object phoneCode(HttpSession session,String phone,String phoneCode,Model model){
String msg="";
Attribute("phone").equals(phone)&&Attribute("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就匹配不到之前的随机数了. 对了,第三⽅短信平台⽤的"中国⽹建".