校驗用戶名是否存在(ajax+jackson)

只是簡單的仿某度註冊的用戶名輸入離焦後檢驗css

 

 目錄結構html

 

 

 

 沒有涉及到數據庫java

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>校驗用戶名是否存在</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script>
        //頁面加載完成後
        $(function () {
            //給用戶名輸入框定義一個離焦事件
            $("#username").blur(function () {
                //獲取文本輸入框的值
                var username=$(this).val();
                /* 指望服務器端響應回來的數據格式是這樣的(json):
                        {"userExit":true,"msg":"此用戶太受歡迎,請換一個"}
                        {"userExit":false,"msg":"用戶名可用"}
                 */
                $.get("findUsernameServlet",{username:username},function (data) {
                    alert(data.msg);
                    var span = $("#s_username")
                    //判斷響應回來的數據的鍵userExit是否爲true
                    if (data.usernameExsit){
                        //true 用戶名存在
                        span.css("color","red");
                        span.html(data.msg);
                    } else {
                        //false  用戶名不存在
                        span.css("color","green");
                        span.html(data.msg);
                    }
                },"json");
            });
        });
    </script>
</head>
<body>
    <form action="" method="get">
        <input type="text" id="username" name="username" placeholder="請輸入用戶名">
        <span id="s_username"></span><br>
        <input type="password" name="password" placeholder="請輸入密碼"><br>
        <input type="submit" value="註冊">
    </form>
</body>
</html>
View Code
java servlet
@WebServlet("/findUsernameServlet")
public class FindUsernameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        response.setContentType("application/json;charset=utf-8");

        Map<String,Object> map=new HashMap<>();
        /*判斷瀏覽器客戶端傳過來的數據  username
           true   {"userExit":true,"msg":"此用戶太受歡迎,請換一個"}
           false    {"userExit":false,"msg":"用戶名可用"}
             */
        if ("tom".equals(username)){
            map.put("usernameExsit",true);
            map.put("msg","此用戶太受歡迎,請換一個");
        }else {
            map.put("usernameExsit",false);
            map.put("msg","用戶名可用");
        }
        //java:map-->json
        ObjectMapper mapper=new ObjectMapper();
        mapper.writeValue(response.getWriter(),map);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
View Code
相關文章
相關標籤/搜索