Struts2 ajax+json账户唯一性验证
本节使用struts2框架,通过ajax+json,在页面不刷新的情况下实现账户唯一性验证。
使用struts2框架——json的核心包和依赖包如下:
当我们导入了以上两个包时,就可以在struts.xml定义我们的<package>
<pre name="code" class="html"><package name="json" namespace="/" extends="json-default" > <action name="empJudgement" class="org.great.action.emp.EmpAction" method="judgement"> <result type="json"> <param name="root">flag</param> </result> </action> </package>
我们可以在struts2-json-puugin的jar包里面的xml看到它的定义
接下来,看jsp代码:
<body> <form action="emp_Emp_add" method="post"> <label>姓名:</label><input id="ename" type="text" name="emp.ename" onblur="judgement()"><span id="sp"></span><br/> <label>工作:</label><input type="text" name="emp.job"><br/> <input type="submit" value="提交"> </form> </body> <script type="text/javascript"> function judgement(){ var ename = $("#ename").val(); $.ajax({ type:"post", url:"empJudgement", data:"ename="+ename, cache:false, error : function(){ alert("请重试"); }, success: function(data){ alert(data); if(data){ $("#sp").text("可以注册"); }else{ $("#sp").text("账户已存在"); } } }) } </script>
<package name="json" namespace="/" extends="json-default" > <action name="empJudgement" class="org.great.action.emp.EmpAction" method="judgement"> <result type="json"> <param name="root">flag</param> </result> </action>
public String judgement(){ EmpBean bean = DaoFactory.getEmpDao().findEmpBean_ByName(ename); if(null == bean){ flag = true; }else{ flag = false; } return "success"; }
private PreparedStatement pre = null; private ResultSet rs = null; public EmpBean findEmpBean_ByName(String ename) { EmpBean empBean = null; Connection conn = DBUtils.getConn(); String sql = "select * from emp where ename = ?"; try { pre = conn.prepareStatement(sql); pre.setString(1, ename); rs = pre.executeQuery(); if(rs.next()){ empBean = new EmpBean(); empBean.setEmpNo(rs.getInt(1)); empBean.setEname(rs.getString(2)); empBean.setJob(rs.getString(3)); empBean.setMgr(rs.getInt(4)); empBean.setHireDate(rs.getString(5)); empBean.setSal(rs.getInt(6)); empBean.setComm(rs.getInt(7)); empBean.setDeptNo(rs.getInt(8)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtils.close(conn, pre, rs); } return empBean; }