Ajax实现登录时的用户名验证(Servlet 响应)

登录提交表单使用 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="登   录" >
    ${error}
</form>

<!--index.jsp-->
<h3 style='color:#00f'>亲爱的${user.name},欢迎您!</h3>
<p>现在的时间是:<% out.println(new java.util.Date()); %></p>

2. Ajax 引擎请求服务器及接受响应

//javascript
var xmlHttp;
var userId = document.getElementById("userId");
var passwd = document.getElementById("passwd");
var info = document.getElementsByClassName("info");
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;
        }
    };
}
function 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;
        }
    };
}

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);
            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);      
        }
    }
}

待续 …

posted @ 2017-04-05 01:43  Noelli  阅读(547)  评论(0编辑  收藏  举报