码迷,mamicode.com
首页 > 其他好文 > 详细

案例7-用户名异步校验

时间:2018-02-02 00:48:26      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:bsp   let   事件   xtend   prot   dao   rda   response   post   

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-用户名异步校验

标签:bsp   let   事件   xtend   prot   dao   rda   response   post   

原文地址:https://www.cnblogs.com/jepson6669/p/8401696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!