Ajax實現登入時的使用者名稱驗證(Servlet 響應)

來源:互聯網
上載者:User

登入提交表單使用 POST 請求進行驗證及轉寄;
輸入使用者名稱(是否正確)及密碼(是否為空白) 使用 GET 請求進行驗證; 1. 登入介面及首頁

<!--login.jsp--><form action="login" method="POST">    <div>        <input type="text" name="username" id="userId" placeholder="使用者名稱">        <span class="info"></span>    </div>    <div>        <input type="password" name="password" id="passwd" placeholder="密碼">    </div>    <input type="submit" value="登   錄"  id="submit" >    <span class="hint">${error} </span></form><!--index.jsp--><h3 style='color:#00f'>親愛的${user.name},歡迎您。</h3><p>現在的時間是:<% out.println(new java.util.Date()); %></p>
2. Ajax 引擎請求伺服器及接受響應
//javascriptvar xmlHttp;var userId = document.getElementById("userId");var passwd = document.getElementById("passwd");var info = document.getElementsByClassName("info");var submit = document.getElementById("submit");var hint = document.getElementsByClassName("hint")[0];userId.onblur = checkUser;passwd.onblur = checkPwd;function createXMLHttpRequest() {    //檢查是否支援 ActiveXObject 控制項(IE瀏覽器)    if(window.ActiveXObject) {        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    } else if(window.XMLHttpRequest) {        xmlHttp = new XMLHttpRequest();     }}//檢查使用者名稱是否正確或存在function checkUser() {    createXMLHttpRequest();    var url = "login?username="+userId.value;    xmlHttp.open("GET", url, true);    xmlHttp.send(null);    xmlHttp.onreadystatechange = function() {        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {            info[0].innerHTML = xmlHttp.responseText;        }    };}//檢查密碼是否為空白或nullfunction checkPwd() {    createXMLHttpRequest();    var url = "login?password="+passwd.value;    xmlHttp.open("GET", url, true);    xmlHttp.send(null);    xmlHttp.onreadystatechange = function() {        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {            info[1].innerHTML = xmlHttp.responseText;        }    };}//提交登入之前檢查,若使用者名稱或密碼為空白,則取消請求submit.onclick = function(){    if(userId.value==""){        info[0].innerHTML = "";        info[1].innerHTML = "";        hint.innerHTML = "使用者名稱不可為空。";        return false;    } else if(passwd.value==""){        info[0].innerHTML = "";        info[1].innerHTML = "";        hint.innerHTML = "密碼不可為空。";        return false;           }}
3. Servlet 對請求作出響應

當 username 為空白時,按 tab 鍵使使用者名稱輸入框失去焦點,此時觸發GET請求,url 尾碼為: ?username=,
即:username=="", password==null

當 username 不為空白,按 tab 鍵使使用者名稱輸入框失去焦點,並觸發GET請求,url 尾碼為: ?username=xxx,
即:username=="xxx", password==null

若再按 tab 鍵使密碼輸入框又失去焦點,這時繼續GET請求,url 尾碼為: ?password=,
即:username==null, password==""

//LoginServlet.java@WebServlet("/login")public class LoginServlet extends HttpServlet {    ......    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();         // username、password 可能為null, 可能不為null        if(request.getParameter("username") == "") {              //?username=            if(request.getParameter("password") == null) {                out.print("使用者名稱不可為空。");            }         } else if(request.getParameter("username") == null) {             if(request.getParameter("password") == ""){                //?password=                out.print("密碼不可為空。");               }           } else {             //?username=xxx            String name = request.getParameter("username");                 if(!name.equals("admin")) {                if(request.getParameter("password") == null) {                    out.print("使用者名稱不存在。");                   }                       }        }    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();         String name = request.getParameter("username");        String pwd = request.getParameter("password");        if(name.equals("admin") && pwd.equals("admin")) {            User user = new User(name,pwd);  //user對象            HttpSession session = request.getSession();            session.setAttribute("user", user);                 RequestDispatcher rd = request.getRequestDispatcher("/");            rd.forward(request, response);        } else {            request.setAttribute("error", "使用者名稱或密碼錯誤。");            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");            rd.forward(request, response);              }    }}
//User.javapublic class User {    String name;    String pwd;    public User(String name, String pwd) {        this.name = name;        this.pwd = pwd;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }}

待續 …

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.