第一步:
导入jquery
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
第二步:
建个表单和输入框
<body> <form > 输入用户名:<input type="text" id="username" > </form> </body>
第三步:
写JS代码,blur()方法
<script type="text/javascript"> $(function(){ $("#username").blur(function(){ //1、失去焦点,获得输入框的内容 var usernameInput = $(this).val(); //2、去服务端校验该用户名是否存在 $.post( "${pageContext.request.contextPath}/checkUsernameServlet", {"username":usernameInput}, function(data){ var isExist = data.isExist; //3、根据返回的isExist动态地显示信息 var usernameInfo = ""; if(isExist){ //该用户存在 usernameInfo = "该用户名已经存在" }else{ usernameInfo = "该用户名可以使用" } $("#usernameInfo").html(usernameInfo); }, "json" ); }); }); </script>
第四步:
在web层创建Servlet(我分为web,service,dao和domain,domain负责封装,因为只有一个username参数,就没用到domain)
以JSON格式返回isExist
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(); } response.getWriter().write("{\"isExist\":"+isExist+"}"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
第五步:
创建Service
public class UserService { public boolean checkUsername(String username) throws SQLException { UserDao dao = new UserDao(); Long isExist = dao.checkUsername(username); return isExist>0?true:false; } }
第六步:
创建Dao(注:使用的是C3P0和DBUtils,所以要导入各种包和配置文件)
public class UserDao { public Long checkUsername(String username) throws SQLException { QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource()); String sql = "select count(*) from user where username = ?"; Long query = (Long) runner.query(sql, new ScalarHandler(),username); return query; } }
第七步,代码完成并测试
原文地址:https://www.cnblogs.com/yg1024/p/8366495.html
时间: 2024-10-11 15:39:52