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