SSH_框架整合5--验证用户名是否可用
1 emp-input.jsp中编写ajax验证用户名是否可用:
1 <script type="text/javascript" SRC="scripts/jquery-1.7.2.js"></script> 2 <script type="text/javascript"> 3 $(function(){ 4 $(":input[name=lastName]").change(function(){ 5 var val = $(this).val(); 6 val = $.trim(val); 7 var $this = $(this); 8 9 if(val != ""){ 10 //把当前节点后面的所有 font 兄弟节点删除 11 $this.nextAll("font").remove(); 12 13 var url="emp-validateLastName"; 14 var args={"lastName":val,"time":new Date()}; 15 $.post(url,args,function(data){ 16 //姓名可用 17 if(data == "1"){ 18 $this.after("<font color='green'>LastName可用!</font>"); 19 } 20 //不可用 21 else if(data == "0"){ 22 $this.after("<font color='red'>LastName不可用!</font>"); 23 } 24 //服务器错误 25 else{ 26 alert("服务器错误!"); 27 } 28 }); 29 }else{ 30 alert("lastName不能为空!"); 31 $(this).val(""); 32 //$(this).focus(); 33 } 34 }); 35 }) 36 </script>
2 完善类:底层编写代码实现验证的方法:
(1)EmployeeDao.java
1 //4 校验注册的姓名是否可用 2 public Employee getEmployeeByLastName(String lastName){ 3 String hql = "FROM Employee e WHERE e.lastName = ?"; 4 Query query = getSession().createQuery(hql).setString(0, lastName); 5 Employee employee = (Employee) query.uniqueResult(); 6 //System.out.println("***"+employee.getDepartment().getClass().getName()); 7 return employee; 8 }
(2)EmployeeService.java
1 //4 校验注册的姓名是否可用 2 public boolean lastNameIsValid(String lastName){ 3 //在数据库中查完结果为null,说明没有被注册过 4 return employeeDao.getEmployeeByLastName(lastName) == null; 5 }
(3)EmployeeAction.java
1 //5 校验注册的姓名是否可用 2 private String lastName; 3 4 public void setLastName(String lastName) { 5 this.lastName = lastName; 6 } 7 8 public String validateLastName() throws UnsupportedEncodingException{ 9 if(employeeService.lastNameIsValid(lastName)){ 10 inputStream = new ByteArrayInputStream("1".getBytes("UTF-8")); 11 }else{ 12 inputStream = new ByteArrayInputStream("0".getBytes("UTF-8")); 13 } 14 return "ajax-success"; 15 } 16
其中delete()方法的return修改为:return "ajax-success";
3 applicationContext.xml中修改为只读:
<tx:method name="lastNameIsValid" read-only="true"/>