DIV CSS 佈局教程網

Ajax 打造帶驗證碼的登入頁:圖片局部刷新與表單驗證實作
編輯:AJAX基礎知識     

現在的登入頁大多具備三個要素:驗證碼、驗證碼可點擊局部刷新、以及以 Ajax 完成登入。用 Ajax 登入最明顯的好處是速度快、網址不變;使用者不會看到整頁重載,體驗自然順暢。今天也很少再用 form 的 post 直接提交了。

以下把這三件事拆開實作。運行畫面如下:

一、驗證碼的局部刷新

後端產生驗證碼的部分在上一篇已說明,這裡聚焦在如何讓 img 的 src 換掉以達到刷新的效果。

HTML:

<p>
  <label class="lbright">驗證碼:</label>
  <span>
    <input type="text" name="validcode" style="width:70px; vertical-align:middle;" id="validcode"/>
    <img id="codePic" src="https://127.0.0.1:8888/TP/codePic" width="60" height="21"
         style="vertical-align:middle;cursor:pointer;"/>
  </span>
  <a class="blurry" id="newPic" onclick="getPic();">看不清楚,換一張</a>
</p>

JS:

<script type="text/javascript">
function getPic() {
    $("#codePic").attr("src", "https://127.0.0.1:8888/TP/codePic?flag=" + Math.random());
}
</script>

整段程式碼的關鍵就在 ?flag=" + Math.random() 這一段。如果不加上這個每次都不同的參數,瀏覽器會認為網址沒變而直接沿用快取裡的圖片,畫面自然不會更新——這正是先前文章談過的快取問題在圖片上的另一個切面。

而 codePic 其實是一個 action,它負責用 Java 的繪圖 API 畫出驗證碼、打包成圖片後回傳給 img。

二、用 Bootstrap Modal 做提示對話框

登入送出前需要先檢查帳號、密碼是否為空、長度是否合規等,若不通過就跳出提示。驗證邏輯用 JS,對話框則用 Bootstrap 的 modal。

<div class="modal" id="mymodal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">×</span><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title">親,您好</h4>
      </div>
      <div class="modal-body" id="dialogs"><p></p></div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal"
          style="color:#FFFFFF;background-color:#FB8F02;text-align:center;padding:10px;
                 border:1px solid #dedede;border-radius:15px;vertical-align:middle;">
          我知道了
        </button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

驗證部分:

<script type="text/javascript">
function dialog() {
    $("#mymodal").modal("toggle");
}

function login() {
    var userName  = document.getElementById("username").value;
    var pwd       = document.getElementById("password").value;
    var validcode = document.getElementById("validcode").value;
    var matchResult = true;

    if (userName == "") {
        document.getElementById("dialogs").innerHTML = "<h3>用戶賬號不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (pwd == "") {
        document.getElementById("dialogs").innerHTML = "<h3>用戶密碼不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (validcode == "") {
        document.getElementById("dialogs").innerHTML = "<h3>驗證碼不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (userName.length < 6 || userName.length > 20) {
        document.getElementById("dialogs").innerHTML = "<h3>用戶名長度應在 6 到 20 個字符之間!</h3>";
        dialog(); matchResult = false;
    } else if (pwd.length < 6 || pwd.length > 20) {
        document.getElementById("dialogs").innerHTML = "<h3>密碼長度應在 6 到 20 個字符之間!</h3>";
        dialog(); matchResult = false;
    }
    return matchResult;
}
</script>

三、用 Ajax 完成登入

登入按鈕:

<div class="submitcon">
  <input type="button" value="登 錄"
    style="height:45px;width:130px;margin-top:15px;color:#FFFFFF;background-color:#FB8F02;
           font-size:20px;padding:5px;border:3px solid #dedede;border-radius:15px;
           vertical-align:middle;text-align:center;"
    onclick="login();"/>
</div>

送出邏輯(此處使用 jQuery 封裝的 $.post()):

<script type="text/javascript">
function login() {
    var userName  = document.getElementById("username").value;
    var pwd       = document.getElementById("password").value;
    var validcode = document.getElementById("validcode").value;

    // ...(此處沿用上節的驗證,通過後才繼續)

    if (matchResult == true) {
        $.post("https://127.0.0.1:8888/TP/usersAction?method=login",
            { usersName: userName, password: pwd, validcode: validcode },
            function (data, status) {
                var error = data.error;
                var result = data.result;
                getPic();   // 不論結果如何都換一張新驗證碼

                if (error == "error") {
                    document.getElementById("dialogs").innerHTML = "<h3>驗證碼錯誤,請重新輸入!</h3>";
                    dialog();
                }
                if (result == "0") {
                    document.getElementById("dialogs").innerHTML = "<h3>您輸入的用戶名不存在!</h3>";
                    document.getElementById("username").value = "";
                    dialog();
                } else if (result == "1") {
                    document.getElementById("dialogs").innerHTML = "<h3>您輸入的密碼錯誤,請重新輸入!</h3>";
                    document.getElementById("password").value = "";
                    dialog();
                } else if (result == "2") {
                    document.getElementById("dialogs").innerHTML = "<h3>您的管理員權限不夠!</h3>";
                    dialog();
                } else if (result == "3") {
                    location.href = "https://127.0.0.1:8888/TP/main.jsp";
                }
            }, "json");
    }
}
</script>

location.href 這裡的作用等同重定向,登入成功後跳轉到主頁面。

login.jsp 完整內容

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>無標題文檔</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/global.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>

<!-- 提示對話框 -->
<div class="modal" id="mymodal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">×</span><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title">親,您好</h4>
      </div>
      <div class="modal-body" id="dialogs"><p></p></div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal"
          style="color:#FFFFFF;background-color:#FB8F02;text-align:center;padding:10px;
                 border:1px solid #dedede;border-radius:15px;vertical-align:middle;">
          我知道了
        </button>
      </div>
    </div>
  </div>
</div>

<div class="logincontainer">
  <div class="logintitle">大學二手交易平台管理系統</div>
  <div class="loginbg">
    <div class="loginfmbg">
      <div class="sysname">BBW綜合管理系統</div>
      <div class="loginfm">
        <p>
          <label class="lbright">用戶名:</label>
          <span class="spinput"><input type="text" name="usersName" id="username"/></span>
        </p>
        <p>
          <label class="lbright">密 碼:</label>
          <span class="spinput"><input type="password" name="password" id="password"/></span>
        </p>
        <p>
          <label class="lbright">驗證碼:</label>
          <span>
            <input type="text" name="validcode" style="width:70px;vertical-align:middle;" id="validcode"/>
            <img id="codePic" src="https://127.0.0.1:8888/TP/codePic" width="60" height="21"
                 style="vertical-align:middle;cursor:pointer;"/>
          </span>
          <a class="blurry" id="newPic" onclick="getPic();">看不清楚,換一張</a>
        </p>
      </div>

      <div class="submitcon">
        <input type="button" value="登 錄" onclick="login();"
          style="height:45px;width:130px;margin-top:15px;color:#FFFFFF;background-color:#FB8F02;
                 font-size:20px;padding:5px;border:3px solid #dedede;border-radius:15px;
                 vertical-align:middle;text-align:center;">
      </div>
    </div>
  </div>
  <div class="copyright">Copyright 2015-2016 林志強 版權所有</div>
</div>

<script type="text/javascript">
function getPic() {
    $("#codePic").attr("src", "https://127.0.0.1:8888/TP/codePic?flag=" + Math.random());
}
function dialog() {
    $("#mymodal").modal("toggle");
}
function login() {
    var userName  = document.getElementById("username").value;
    var pwd       = document.getElementById("password").value;
    var validcode = document.getElementById("validcode").value;
    var matchResult = true;

    if (userName == "") {
        document.getElementById("dialogs").innerHTML = "<h3>用戶賬號不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (pwd == "") {
        document.getElementById("dialogs").innerHTML = "<h3>用戶密碼不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (validcode == "") {
        document.getElementById("dialogs").innerHTML = "<h3>驗證碼不能為空!</h3>";
        dialog(); matchResult = false;
    } else if (userName.length < 6 || userName.length > 20) {
        document.getElementById("dialogs").innerHTML = "<h3>用戶名長度應在 6 到 20 個字符之間!</h3>";
        dialog(); matchResult = false;
    } else if (pwd.length < 6 || pwd.length > 20) {
        document.getElementById("dialogs").innerHTML = "<h3>密碼長度應在 6 到 20 個字符之間!</h3>";
        dialog(); matchResult = false;
    }

    if (matchResult == true) {
        $.post("https://127.0.0.1:8888/TP/usersAction?method=login",
            { usersName: userName, password: pwd, validcode: validcode },
            function (data, status) {
                var error = data.error;
                var result = data.result;
                getPic();

                if (error == "error") {
                    document.getElementById("dialogs").innerHTML = "<h3>驗證碼錯誤,請重新輸入!</h3>";
                    dialog();
                }
                if (result == "0") {
                    document.getElementById("dialogs").innerHTML = "<h3>您輸入的用戶名不存在!</h3>";
                    document.getElementById("username").value = "";
                    dialog();
                } else if (result == "1") {
                    document.getElementById("dialogs").innerHTML = "<h3>您輸入的密碼錯誤,請重新輸入!</h3>";
                    document.getElementById("password").value = "";
                    dialog();
                } else if (result == "2") {
                    document.getElementById("dialogs").innerHTML = "<h3>您的管理員權限不夠!</h3>";
                    dialog();
                } else if (result == "3") {
                    location.href = "https://127.0.0.1:8888/TP/main.jsp";
                }
            }, "json");
    }
}
</script>
</body>
</html>

幾個值得留意的細節

登入失敗一定要換驗證碼。程式中無論成功失敗都呼叫 getPic(),這點很重要——若驗證碼能用同一張圖重試無限次,它就失去了阻擋暴力破解的意義。理想的作法是伺服器端在驗證後即失效該 captcha,而非只靠前端換圖。

不要用「帳號不存在」這種訊息。明確區分「帳號不存在」與「密碼錯誤」會讓攻擊者得以枚舉出哪些帳號已註冊。實務上建議一律回覆「帳號或密碼錯誤」。

別忘了伺服器端也要驗證。範例中的長度與必填檢查都在前端,但使用者完全可以繞過前端直接發請求。所有驗證都必須在後端重做一遍,驗證碼比對也必須在後端 session 中進行。

傳輸必須走 HTTPS。帳號密碼以明文 HTTP 傳送,等於在同一網路的任何人都能攔截。範例中的 https://127.0.0.1:8888 僅供本地測試,正式環境請改用 HTTPS,並在登入成功後設定 HttpOnly 與 Secure 的 Cookie。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved