其他分享
首页 > 其他分享> > 校验用户名是否存在案例

校验用户名是否存在案例

作者:互联网

案例

regist.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <script src="js/jquery-3.6.0.min.js"></script>

    <script>
        //在页面加载完成后执行
        $(function () {
            //给username绑定blur事件
            $("#username").blur(function () {
                //获取username输入框的值
                var username = $(this).val();
                //发送ajax请求
                $.get("/findUserServlet", {username: username}, function (data) {
                    var span = $("#s_username");
                    if (data.userExsit) {
                        span.css("color", "red");
                        span.html(data.msg);
                    } else {
                        span.css("color", "green");
                        span.html(data.msg);
                    }
                },"json");
            });
        });
    </script>
</head>
<body>
    <form>
        用户名:<input type="text" id="username" name="username" placeholder="请输入用户名">
        <span id="s_username"></span>
        <br><br>
        密码:<input type="password" name="password" placeholder="密码"><br><br>
        <input type="submit" value="注册">
    </form>
</body>
</html>

FindUserServlet

package com.ailyt.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "findUserServlet", value = "/findUserServlet")
public class FindUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("test/html;charset=utf-8");
        String username = request.getParameter("username");

        HashMap<String, Object> map = new HashMap<>();

        if ("tom".equals(username)) {
            map.put("userExsit",true);
            map.put("msg", "此用户名太受欢迎请换一个");
        } else {
            map.put("userExsit",false);
            map.put("msg", "用户名可用");
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getWriter(),map);
    }
}

标签:username,map,用户名,span,校验,案例,html,import,response
来源: https://www.cnblogs.com/ailhy/p/16609909.html