案例7-用户名异步校验

Posted jepson6669

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例7-用户名异步校验相关的知识,希望对你有一定的参考价值。

1 register.jsp代码

<script type="text/javascript">
    $(function(){
        
        //为输入框绑定事件
        $("#username").blur(function(){
            //1、失去焦点获得输入框的内容
            var usernameInput = $(this).val();
            //2、去服务端校验该用户名是否存在---ajax
            $.post(
                "${pageContext.request.contextPath}/checkUsername",
                {"username":usernameInput},
                function(data){
                    var isExist = data.isExist;
                    //3、根据返回的isExist动态的显示信息
                    var usernameInfo = "";
                    if(isExist){
                        //该用户存在
                        usernameInfo = "该用户名已经存在";
                        $("#usernameInfo").css("color","red");
                    }else{
                        usernameInfo = "该用户可以使用"
                        $("#usernameInfo").css("color","green");
                    }
                    $("#usernameInfo").html(usernameInfo);
                    
                },
                "json"
            );
            
            
        });

        
    });
</script>

2 web层

public class CheckUsernameServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //获得要校验的用户名
        String username = request.getParameter("username");
        
        //传递username到service
        UserService service = new UserService();
        boolean isExist = false;
        try {
            isExist = service.checkUsername(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //isExist是Boolean形的,所以不用加引号。
//如果写回去的是一个String类型格式如下
//"{\"namet\":\""+name+"\"}" response.getWriter().write(
"{\"isExist\":"+isExist+"}"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

3 service层

public boolean checkUsername(String username) throws SQLException {
        
        UserDao dao = new UserDao();
        Long isExist = dao.checkUsername(username);
        
        return isExist>0?true:false;
    }

4 dao层

public class UserDao {

    public Long checkUsername(String username) throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from user where username=?";
        Long query = (Long) runner.query(sql, new ScalarHandler(), username);
        return query;
    }

}

 

以上是关于案例7-用户名异步校验的主要内容,如果未能解决你的问题,请参考以下文章

ajax案例_校验用户名

用户名异步校验

AJAX异步校验

案例16-validate自定义校验规则校验用户名是否存在

ES7-Es8 js代码片段

校验用户名是否存在