1.首先在前台的jsp文件中引入jQuery的包,并且得写上文件的路径,文本框的设置
<script src="./js/jquery-1.7.min.js"></script>
<!-- 员工的编号 --> <div class="am-form-group"> <label for="user-name" class="am-u-sm-3 am-form-label">员工编号</label> <div class="am-u-sm-9"> <input type="text" name="no" style="width: 300px; float: left;" id="no" placeholder="请输入员工编号"><span style="color: #F00; float: left; margin-top: 5px;">* </span> <span id="vno" style="padding-top: 10px;"></span> </div> </div> <!-- 所属部门 -->
2.在jsp文件中,写入jquery的代码
<script> //使用ajax来判断员工的编号是否注册 $(function(){ $('#no').blur(function(){//鼠标移开的事件 var no = $('#no').val();//获取文本框中的值 /* alert(no); */ //部分路径 var path = '<%=request.getContextPath()%>'; $.ajax({ type : "post",//提交的方式 url : path + "/employee",//完整的路径 async : false, data : {//传的值和跳转到servlet文件中的那个方法 "no" : no, "action" : "check" }, //如果成功的话,判断编号是否可用 success : function(data) {//在Dao文件中的sql语句已经查询了前台输入的编号有几条,如果1条不可用,如果0条可用 if (data > 0) { $('#vno').text('用户名ID重复,无法使用'); } else {//判断文本框是否为空 if (no == "" || no == null) { $('#vno').text('请输入员工编号'); } else { $('#vno').text('恭喜!此用户ID可以注册'); } } }, error : function() { alert("失败") } }); }) }) </script>
3.在servlet文件中写入方法
else if (action != null && action.equals("check")) { /** * 判断编号是否注册 */ //定义一个print PrintWriter print = response.getWriter(); EmployeeDao employeedao = new EmployeeDao(); //获取前台文本框中的编号 String no = request.getParameter("no"); try {//把Dao文件中返回的数传给shu int shu = employeedao.bianhao(no); //把信息传到前台的data print.print(shu); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } print.flush(); print.close(); }
4.在Dao文件中写入servlet方法中调用的方法
/** * 判断员工编号是否注册过 */ public int bianhao(String no) throws SQLException { //查询前台写入的编号在数据库中存在的数量 String sql = "select count(EM_NO) from task_employee where EM_NO=?"; Connection conn = null; PreparedStatement stmt = null; //定义一个count int count = 0; conn = getConn(); stmt = conn.prepareStatement(sql); stmt.setString(1, no); ResultSet rs = stmt.executeQuery(); //获取文本框中输入的编号在数据库中数量存入到count中 if (rs.next()) { count = rs.getInt(1); } //返回数据库中查询编号存在的数 return count; }
最后的样式