項目做了登錄改密功能需要驗證碼的功能.
思路:頁面點擊獲取驗證碼按鈕,發送請求到后台,攜帶用戶名作為參數.后台做一個servlet查詢該用戶的手機號.生成隨機驗證碼.將驗證碼(+消息)+tel作為參數+其他接口參數拼成url調用第三方服務(雲信).
實現:
1.頁面js方法
function get_code_time(){ var uname = $("#uname").val(); if(!uname){ $("#users").html("請先輸入您的用戶名!");//提示信息 }else{ var data="uname="+uname; $.get("sendCodes",{uname:uname},function(data){ code_time();//記時方法
//根據servlet返回的json判斷短信發送狀態 if(data=="0"){ alert("短信驗證碼發送失敗,請重新獲取"); }else if(data=="1"){ alert("用戶名未注冊"); }else if(data=="2"){ alert("用戶名無效或手機號未注冊"); }else if(data=="3"){ alert("短信發送成功"); }else if(data=="4"){ alert("驗證碼超時"); } }); } }
var wait = 60;
function code_time(){
// alert(567);
if(wait==0){
$("#codes").removeAttr("disabled");//移除獲取驗證碼按鈕的disabled屬性
$("#codes").val("重新獲取驗證碼");
$("#msgs").val("");
wait =60;
}else{
$("#codes").attr("disabled", true);//設置獲取驗證碼按鈕為不可觸發
$("#codes").val("(" + wait + ")秒后獲取驗證碼");
wait--;
setTimeout("code_time()", 1000);
}
}
2.后台servlet:servlet的路徑是上面js方法中的sendCodes
public class SendCodes extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ret="",uname="",tel = ""; uname=request.getParameter("uname"); //判斷用戶名是否為空 if(uname==null || "".equals(uname)){ response.getWriter().write("1"); return; } //通過用戶名找到電話號碼 String sql = "select ccu.tel from table_user tu where tu.user_name= ? "; Session session = new Session(EcConnection.get());//自己封裝的獲取數據庫連接的方法 try{ tel = session.queryForColumn(String.class, sql, uname); }catch (Exception e) { e.printStackTrace(); }finally{ session.close(); }//手機號為空2 if (tel==null || "".equals(tel)) { response.getWriter().write("2"); return; } //生成驗證碼 int Random = (int) ((Math.random()*9+1)*100000);//隨機生成的6位數(驗證碼) //發送到手機 //SMSTest sms=new SMSTest(); String mes= "您的驗證碼:"+String.valueOf(Random)+",有效時間5分鍾" ; String msg = ""; try { //由於服務器不能解析調用發送短信接口拼接的url,
//發送短信,調另一服務,其實就是一個servlet,訪問返回的是調用短信接口的發送狀態碼, Map<String, String> paraMap = new HashMap<String, String>(); paraMap.put("mes", mes); msg = HttpClient.post("http://127.0.0.1:8082/SendSms/semdsms?tel="+tel, paraMap);//自己封裝的httpClientpost方法,下面粘代碼 System.out.println(msg); //如果返回的是錯誤服務錯誤信息 if("發送短信錯誤".equals(msg)){ response.getWriter().write("0"); return; } }catch (Exception e) { e.printStackTrace(); response.getWriter().write("0"); return; } //新建一個實體類對象,把它做為一個容器來放驗證碼,帳號和收取驗證碼時間。服務不關閉,或是30分鍾后就登陸無效 SmsMessageBean b = new SmsMessageBean(uname,Random+"",System.currentTimeMillis()); EcContainer.RandomMap.put(uname, b); response.getWriter().write("3"); }
HttpClient訪問的http://127.0.0.1:8082/SendSms/semdsms的servlet:service方法
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String tel = req.getParameter("tel"); String mes = req.getParameter("mes"); SMSTest sms = new SMSTest(); PrintWriter pw = resp.getWriter(); try { String msg = sms.send(mes, tel); pw.write(msg); } catch (Exception e) { e.printStackTrace(); pw.write("發送短信錯誤"); } }
第三方短息接口:
public class SMS{ private static final String addr = "http://api.sms.cn/mt/"; //接口服務注冊的用戶id private static final String userId = "*****"; /* * 如uid是:test,登錄密碼是:123123 pwd=md5(123123test),即 pwd=b9887c5ebb23ebb294acab183ecf0769 線生成地址:http://www.sms.cn/password */
//接口注冊的密碼:經過拼接字符串和md5加密后的結果
private static final String pwd = "-----------------"; private static final String encode = "utf8"; //編碼 public String send(String msgContent, String mobile) throws Exception { //組建請求 String straddr = addr + "?uid="+userId+ "&pwd="+pwd+ "&mobile="+mobile+ //手機號 "&encode="+encode+ "&content=" +URLEncoder.encode(msgContent, "UTF-8"); //編碼格式要對應上,不然就收不到短信 StringBuffer sb = new StringBuffer(straddr);//發送請求 URL url = new URL(sb.toString()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); //返回結果 String inputline = in.readLine(); String msg=inputline.substring(9, 12); System.out.println("smstest="+msg); return msg; } }
自己封裝的httpClient方法: 直接使用即可.
public static String post(String baseUrl, Map<String, String> paramsMap) { StringBuilder doc = new StringBuilder(); try { StringBuilder queryString = new StringBuilder(); for (Iterator<String> it = paramsMap.keySet().iterator(); it .hasNext();) { String paramName = it.next().toString(); Object paramValue = paramsMap.get(paramName); if (paramValue == null) { paramValue = ""; } queryString .append(paramName) .append("=") .append(URLEncoder.encode(paramValue.toString(), encode)) .append("&"); } if (queryString.length() > 0) { queryString.deleteCharAt(queryString.length() - 1); } URL url = new URL(baseUrl); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestMethod("POST"); // 設置參數--begin uc.setDoOutput(true); byte[] b = queryString.toString().getBytes(); uc.getOutputStream().write(b, 0, b.length); uc.getOutputStream().flush(); uc.getOutputStream().close(); // 參數設置--end BufferedReader in = new BufferedReader(new InputStreamReader( uc.getInputStream(), encode)); String line = null; while ((line = in.readLine()) != null) { // 處理特殊字符 line = line.replace("&", "&"); doc.append(line); } } catch (IOException e) { e.printStackTrace(); } return doc.toString(); }