1. 程式人生 > >javaweb專案中實現手機簡訊登入

javaweb專案中實現手機簡訊登入

手機號登入在現在的專案中用的場景非常多,實現起來也不難,今天我們就一起來通過演示實現登入過程。
這裡寫圖片描述

<1>首先需要註冊個第三方的賬戶,比如秒嘀科技等,然後拿到三個引數值:QUERAY_PATH ACCOUNT_SID AUTH_TOKEN
<2>編寫獲取驗證碼類getMessage.java

private static final String QUERAY_PATH="xxxx";
    private static final String ACCOUNT_SID="xxx";
    private static final String AUTH_TOKEN="xxx"
; /** * @Title: getCode * @Description: TODO( 傳送驗證碼 ) * @param @param phone * @param @return 設定檔案 * @return String 返回型別 * @throws */ public static String getCode(String phone){ String ran = smsCode(); String timestamp = getStamp(); String sig = getMD5(ACCOUNT_SID, AUTH_TOKEN, timestamp); String tamp = "您的驗證碼為"
+ran+",請於{2}分鐘內正確輸入,如非本人操作,請忽略此簡訊。"; OutputStreamWriter out = null; BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { URL url = new URL(QUERAY_PATH); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"
); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(10000); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); String args = getArgs(ACCOUNT_SID, tamp, phone, timestamp, sig, "JSON"); out.write(args); out.flush(); br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String temp=""; while ((temp=br.readLine())!=null) { sb.append(temp); } } catch (Exception e) { e.printStackTrace(); } JSONObject json = new JSONObject(sb.toString()); String code = json.getString("respCode"); String defaultrespcode = "00000"; if(defaultrespcode.equals(code)){ return ran; }else{ return code; } } /** * @Title: getArgs * @Description: TODO( 引數拼接 ) * @param @param accountSid * @param @param smsContent * @param @param to * @param @param timestamp * @param @param sig * @param @param respDataType * @param @return 設定檔案 * @return String 返回型別 * @throws */ public static String getArgs(String accountSid,String smsContent,String to,String timestamp,String sig,String respDataType){ return "accountSid="+accountSid+"&smsContent="+smsContent+"&to="+to+"&timestamp="+timestamp+"&sig="+sig+"&respDataType="+respDataType; } /** * @Title: getStamp * @Description: TODO( 獲取時間戳 ) * @param @return 設定檔案 * @return String 返回型別 * @throws */ public static String getStamp(){ return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); } /** * @Title: getMD5 * @Description: TODO(sig簽名 ) * @param @param sid * @param @param token * @param @param timestamp * @param @return 設定檔案 * @return String 返回型別 * @throws */ public static String getMD5(String sid,String token,String timestamp){ StringBuilder sBuilder = new StringBuilder(); String source = sid + token + timestamp; try { MessageDigest instance = MessageDigest.getInstance("MD5"); byte[] digest = instance.digest(source.getBytes()); for (byte b : digest) { String hexString = Integer.toHexString(b&0xff); if(hexString.length()==1){ sBuilder.append("0"+hexString); }else{ sBuilder.append(hexString); } } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sBuilder.toString(); } /** * @Title: smsCode * @Description: TODO( 產生驗證碼) * @param @return 設定檔案 * @return String 返回型別 * @throws */ public static String smsCode(){ String random = new Random().nextInt(1000000)+""; if(random.length()!=6){ return smsCode(); }else{ return random; } }

<3> 編寫servlet

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String phone = req.getParameter("phone");   
        String code = GetMessage.getCode(phone);
        //手機號登入後
        HttpSession session = req.getSession();
        PrintWriter out = resp.getWriter();
        //檢查手機號是否註冊過
        checkPhoneDao checkPhoneDao = new checkPhoneImpl();
        boolean results = checkPhoneDao.checkPhone(phone);
        if(!results){
            out.print(code);
            session.setAttribute("name", "phone");
        }else {
            out.print("此手機號沒有被註冊");
        }
        out.close();
    }

<4> dao 層實現 的方法

@Override
    public boolean checkPhone(String phone) {
        String sql = "select username from user where phone=?";
        List<Map<String, Object>> queryForList = DbUtil.queryForList(sql, phone);
        if(queryForList.isEmpty()){
            return true;
        }
        return false;
    }

到此,簡訊登入的功能已經實現了,大家可以按照我的思路嘗試去實現。注:由於有的小夥伴沒有框架基礎,所以演示使用jsp+servlet+jdbc實現的。有不懂的可以聯絡QQ:2217087909。