实例:SSH结合Easyui实现Datagrid的新增功能和Validatebox的验证功能.

先看一下实现的效果:

      (1)点击添加学生信息按键后跳出对话框,其中的学生主键和姓名不能为空,而且学生主键不能和数据库中已有的重复。

 

(2)当输入已有的学生信息的时候,提示已被使用

 

(3)当操作人员不顾提示,强行提交的时候。系统拒绝提交,并且跳出提示框。

 

(4)当操作人员正常操作,提交后会自动刷新,在表格中按照从小到大的顺序排列出来。

 

具体实现步骤:

1、依然是使用SSH框架,数据库表没有新增,所以整体的结果基本不变。将原来的index.jsp中的JavaScript部分划分到index.js中。

 

2、web.xm、applicationContext.xml、Student.javaStudent.hbm.xml、连接数据库的applicationContext_db.xml、Spring依赖注入的applicationContext_bean.xml这些配置文件和上篇博客一模一样,保持不变。SSH的耦合度的优势在慢慢突显。

 

3、在StudentService.java中编写接口,新增操作的方法一定要以save开头,因为在applicationContext_db.xml配置中已经限定,或者你去该applicationContext_db.xml的配置

[java]  view plain  copy
  1. <span style="font-size:18px;">package com.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.model.Student;  
  6.   
  7. public interface StudentService {  
  8.      public List getStudentList(String page,String rows) throws Exception;//根据第几页获取,每页几行获取数据   
  9.      public int getStudentTotal() throws Exception;//统计一共有多少数据  
  10.      public void saveStudent(Student student)throws Exception;//新增学生信息   
  11.      public String queryBy_unique(String table,String field ,String parameter) throws Exception;//验证唯一性  
  12. }  
  13. </span>  


 

4、在StudentServiceImpl.java的类中编写接口的实现类,验证方法queryBy_unique传入三个参数:表名,字段名,字段对应的参数。所以可以做成通用的验证方法,而不是针对某张表的某个字段的验证。

[java]  view plain  copy
  1. package com.serviceImpl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.SessionFactory;  
  7.   
  8. import com.model.Student;  
  9. import com.service.StudentService;  
  10.   
  11. public class StudentServiceImpl implements StudentService {  
  12.     private SessionFactory sessionFactory;  
  13.       
  14.     // 根据第几页获取,每页几行获取数据  
  15.     public List getStudentList(String page, String rows) {  
  16.           
  17.         //当为缺省值的时候进行赋值  
  18.         int currentpage = Integer.parseInt((page == null || page == "0") ? "1": page);//第几页  
  19.         int pagesize = Integer.parseInt((rows == null || rows == "0") ? "10": rows);//每页多少行  
  20.         //查询学生信息,顺便按学号进行排序  
  21.         List list = this.sessionFactory.getCurrentSession().createQuery("from Student  order by studentid")  
  22.                        .setFirstResult((currentpage - 1) * pagesize).setMaxResults(pagesize).list();  
  23.         //setFirstResult 是设置开始查找处。setFirstResult的值 (当前页面-1)X每页条数  
  24.         //设置每页最多显示的条数  setMaxResults每页的条数了  
  25.         return list;  
  26.     }  
  27.   
  28.     // 统计一共有多少数据  
  29.     public int getStudentTotal() throws Exception {  
  30.         return this.sessionFactory.getCurrentSession().find("from Student").size();  
  31.     }  
  32.       
  33.     // 新增学生信息  
  34.     public void saveStudent(Student student) throws Exception {  
  35.         this.sessionFactory.getCurrentSession().save(student);  
  36.           
  37.     }  
  38.       
  39.     //判断是否具有唯一性  
  40.     public String queryBy_unique(String table,String field ,String parameter) throws Exception {  
  41.         System.out.println("===============验证唯一性=========");  
  42.         String s="select * from "+table +" t where t."+field+"='"+parameter+"'";  
  43.         System.out.println("SQL语句:"+s);  
  44.         Query query = this.sessionFactory.getCurrentSession().createSQLQuery(s);  
  45.          
  46.         int n=query.list().size();  
  47.         if(n==0)//如果集合的数量为0,说明没有重复,具有唯一性  
  48.         {  
  49.           return "1";//返回值为1,代表具有唯一性      
  50.         }         
  51.         return "0";//返回值为0,代表已经有了,重复了  
  52.     }  
  53.       
  54.     public SessionFactory getSessionFactory() {  
  55.         return sessionFactory;  
  56.     }  
  57.   
  58.     public void setSessionFactory(SessionFactory sessionFactory) {  
  59.         this.sessionFactory = sessionFactory;  
  60.     }  
  61.       
  62.       
  63. }  


5、在控制层StudentAction.java中编写:

[java]  view plain  copy
  1. package com.action;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import net.sf.json.JSONObject;  
  10.   
  11. import org.apache.log4j.Logger;  
  12. import org.apache.struts2.ServletActionContext;  
  13.   
  14. import com.model.Student;  
  15. import com.service.StudentService;  
  16.   
  17. public class StudentAction {  
  18.     static Logger log = Logger.getLogger(StudentAction.class);  
  19.     private JSONObject jsonObj;  
  20.     private String rows;// 每页显示的记录数  
  21.     private String page;// 当前第几页  
  22.     private StudentService student_services;//String依赖注入  
  23.     private Student student;//学生  
  24.     private String parameter;//参数  
  25.     private String table;//表名  
  26.     private String field;//字段  
  27.       
  28.     //查询出所有学生信息  
  29.     public String allInfo() throws Exception {  
  30.         log.info("查询出所有学生信息");  //引用到log4j你应该加入  log4j的配置文件,不然用System.out.println();来替换  
  31.           
  32.         List list = student_services.getStudentList(page, rows);//传入参数页码和行数,获取当前页的数据  
  33.         this.toBeJson(list,student_services.getStudentTotal());//调用自己写的toBeJson方法转化为JSon格式  
  34.   
  35.         return null;  
  36.     }  
  37.       
  38.     //新增学生信息  
  39.     public String add() throws Exception{  
  40.         log.info("新增学生信息");  
  41.   
  42.         student_services.saveStudent(student);  
  43.         return null;  
  44.     }  
  45.       
  46.     //查询唯一性  
  47.     public String verify() throws Exception{  
  48.         log.info("ACTION验证唯一性");  
  49.         String s = student_services.queryBy_unique(table,field ,parameter);  
  50.         log.info("结果:" + s);  
  51.           
  52.         //将验证的结果返回JSP页面,s为1代表没有重复,为0代表有重复  
  53.         HttpServletResponse response = ServletActionContext.getResponse();  
  54.         response.setContentType("text/html;charset=utf-8");  
  55.         PrintWriter out = response.getWriter();  
  56.         out.print(s);  
  57.         out.flush();  
  58.         out.close();  
  59.   
  60.         return null;  
  61.     }  
  62.       
  63.     //转化为Json格式  
  64.        public void toBeJson(List list,int total) throws Exception{  
  65.             HttpServletResponse response = ServletActionContext.getResponse();  
  66.             HttpServletRequest request = ServletActionContext.getRequest();  
  67.               
  68.             JSONObject jobj = new JSONObject();//new一个JSON  
  69.             jobj.accumulate("total",total );//total代表一共有多少数据  
  70.             jobj.accumulate("rows", list);//row是代表显示的页的数据  
  71.   
  72.             response.setCharacterEncoding("utf-8");//指定为utf-8  
  73.             response.getWriter().write(jobj.toString());//转化为JSOn格式  
  74.               
  75.             log.info(jobj.toString());  
  76.        }  
  77.          
  78.       
  79.     public StudentService getStudent_services() {  
  80.         return student_services;  
  81.     }  
  82.   
  83.     public void setStudent_services(StudentService student_services) {  
  84.         this.student_services = student_services;  
  85.     }  
  86.   
  87.     public void setJsonObj(JSONObject jsonObj) {  
  88.         this.jsonObj = jsonObj;  
  89.     }  
  90.   
  91.     public void setRows(String rows) {  
  92.         this.rows = rows;  
  93.     }  
  94.   
  95.     public void setPage(String page) {  
  96.         this.page = page;  
  97.     }  
  98.   
  99.     public void setStudent(Student student) {  
  100.         this.student = student;  
  101.     }  
  102.   
  103.     public Student getStudent() {  
  104.         return student;  
  105.     }  
  106.   
  107.     public void setParameter(String parameter) {  
  108.         this.parameter = parameter;  
  109.     }  
  110.   
  111.     public void setTable(String table) {  
  112.         this.table = table;  
  113.     }  
  114.   
  115.     public void setField(String field) {  
  116.         this.field = field;  
  117.     }  
  118.          
  119.       
  120.       
  121. }  


 

6、改进Struts.xml配置,完整的action名称是student加上控制层对应的方法名

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC   
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="Easyui" extends="json-default">  
  7.         <!-- 学生信息 -->  
  8.         <action name="student*" class="student_action" method="{1}">   
  9.            <result type="json"> </result>  
  10.         </action>  
  11.     </package>  
  12. </struts>  


7、编写index.jsp页面,将原先的JavaScript代码分离到index.js中

[html]  view plain  copy
  1. <%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4. %>  
  5. <%@ taglib prefix="s" uri="/struts-tags"%>  
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  10. <title>Easyui</title>  
  11.   
  12. <!-- 引入Jquery -->  
  13. <script type="text/javascript" src="<%=path%>/js/easyui/jquery-1.8.0.min.js" charset="utf-8"></script>  
  14. <!-- 引入Jquery_easyui -->  
  15. <script type="text/javascript" src="<%=path%>/js/easyui/jquery.easyui.min.js" charset="utf-8"></script>  
  16. <!-- 引入easyUi国际化--中文 -->  
  17. <script type="text/javascript" src="<%=path%>/js/easyui/locale/easyui-lang-zh_CN.js" charset="utf-8"></script>  
  18. <!-- 引入easyUi默认的CSS格式--蓝色 -->  
  19. <link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui/themes/default/easyui.css" />  
  20. <!-- 引入easyUi小图标 -->  
  21. <link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui/themes/icon.css" />  
  22.   
  23. <!-- 引入对应的JS,切记一定要放在Jquery.js和Jquery_Easyui.js后面,因为里面需要调用他们,建议放在最后面 -->  
  24. <script type="text/javascript" src="<%=path%>/index.js" charset="utf-8"></script>  
  25.   
  26. </head>  
  27. <body>  
  28.     <h2>  
  29.         <b>easyui的DataGrid实例</b>  
  30.     </h2>  
  31.   
  32.     <table id="mydatagrid">  
  33.         <thead>  
  34.             <tr>  
  35.                 <th data-options="field:'studentid',width:100,align:'center'">学生学号</th>  
  36.                 <th data-options="field:'name',width:100,align:'center'">姓名</th>  
  37.                 <th data-options="field:'gender',width:100,align:'center'">性别</th>  
  38.                 <th data-options="field:'age',width:100,align:'center'">年龄</th>  
  39.             </tr>  
  40.         </thead>  
  41.     </table>  
  42.     <!-- 显示添加按钮的Div -->  
  43.     <div id="easyui_toolbar" style="padding: 2px 0px 2px 15px; height: auto">  
  44.         <a href="#" id="easyui_add" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加学生信息</a>  
  45.     </div>  
  46.   
  47.     <!-- 添加学生信息的表单       -->  
  48.     <div id="addDlg" class="easyui-dialog" style="width: 580px; height: 350px; padding: 10px 20px" closed="true" buttons="#addDlgBtn">  
  49.         <form id="addForm" method="post">  
  50.             <table>  
  51.                 <tr>  
  52.                     <td>学生主键</td>  
  53.                     <td>  
  54.                       <input name="student.studentid" id="studentid" class="easyui-validatebox" required="true" missingMessage="学生主键不能为空">  
  55.                     </td>  
  56.                     <td>  
  57.                         <!-- 存放提示重复信息的div -->  
  58.                         <div id="xianshi1" style="float: left"></div>  
  59.                         <div style="float: left"> </div>  
  60.                         <div id="xianshi2" style="font-size: 14px; color: #FF0000; float: left"></div>  
  61.                     </td>  
  62.                 </tr>  
  63.                 <tr>  
  64.                     <td>姓名</td>  
  65.                     <td>  
  66.                       <input name="student.name" id="name" class="easyui-validatebox" required="true" missingMessage="姓名不能为空">  
  67.                     </td>  
  68.                 </tr>  
  69.                 <tr>  
  70.                     <td>性别</td>  
  71.                     <td>  
  72.                         <!-- 使用Easyui中的combobox -->   
  73.                         <select class="easyui-combobox" style="width: 155px;" name="student.gender" id="gender" data-options="panelHeight:'auto'">  
  74.                             <option value="男"></option>  
  75.                             <option value="女"></option>  
  76.                        </select>  
  77.                     </td>  
  78.                 </tr>  
  79.                 <tr>  
  80.                     <td>年龄</td>  
  81.                     <td>  
  82.                       <input name="student.age" id="age" class="easyui-validatebox">  
  83.                     </td>  
  84.                 </tr>  
  85.             </table>  
  86.         </form>  
  87.     </div>  
  88.     <!-- 保存学生信息的按钮,被Jquery设置,当没被调用的时候不显示     -->  
  89.     <div id="addDlgBtn">  
  90.         <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconCls="icon-ok" onclick="add_ok()">确认</a>   
  91.         <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#addDlg').dialog('close')">取消</a>  
  92.     </div>  
  93.   
  94. </body>  
  95. </html>  


8、编写index.jsp页面对应的JS-------index.js

[javascript]  view plain  copy
  1.   var isClickOk=true;//判断的变量  
  2. $(function() {  
  3.     //datagrid设置参数  
  4.     $('#mydatagrid').datagrid({  
  5.         title : 'datagrid实例',  
  6.         iconCls : 'icon-ok',  
  7.         width : 600,  
  8.         pageSize : 5,//默认选择的分页是每页5行数据  
  9.         pageList : [ 5, 10, 15, 20 ],//可以选择的分页集合  
  10.         nowrap : true,//设置为true,当数据长度超出列宽时将会自动截取  
  11.         striped : true,//设置为true将交替显示行背景。  
  12.         collapsible : true,//显示可折叠按钮  
  13.         toolbar:"#easyui_toolbar",//在添加 增添、删除、修改操作的按钮要用到这个  
  14.         url:'studentallInfo.action',//url调用Action方法  
  15.         loadMsg : '数据装载中......',  
  16.         singleSelect:true,//为true时只能选择单行  
  17.         fitColumns:true,//允许表格自动缩放,以适应父容器  
  18.         sortName : 'studentid',//当数据表格初始化时以哪一列来排序  
  19.         sortOrder : 'asc',//定义排序顺序,可以是'asc'或者'desc'(正序或者倒序)。  
  20.         remoteSort : false,  
  21.              frozenColumns : [ [ {  
  22.             field : 'ck',  
  23.             checkbox : true  
  24.         } ] ],   
  25.         pagination : true,//分页  
  26.         rownumbers : true//行数  
  27.     });   
  28.       
  29.     //当点击添加学生信息的时候触发  
  30.     $("#easyui_add").click(function() {  
  31.             $("#xianshi1").empty();//清除上次出现的图标1  
  32.         $("#xianshi2").empty();//清除上次出现的图标2  
  33.         $('#addDlg').dialog('open').dialog('setTitle''添加学生信息');//打开对话框          
  34.         $('#addForm').form('clear');  
  35.     });       
  36.       
  37.     //当光标移开焦点的时候进行重复验证  
  38.     $("#studentid").blur(function(){              
  39.     jQuery.ajax({   //使用Ajax异步验证主键是否重复  
  40.     type : "post",  
  41.     url : "studentverify.action?table=Student&field=studentid¶meter="+$('#studentid').val(),  
  42.     dataType:'json',  
  43.     success : function(s){    
  44.            if($('#studentid').val()==""){//当为主键为空的时候什么都不显示,因为Easyui的Validate里面已经自动方法限制  
  45.               
  46.            }  
  47.            else if( s == "1" )//当返回值为1,表示在数据库中没有找到重复的主键  
  48.         {   isClickOk=true;  
  49.             $("#xianshi1").empty();  
  50.             var txt1="<img src="+"'imgs/agree_ok.gif'"+"/>";//引入打勾图标的路径  
  51.             $("#xianshi1").append(txt1);//在id为xianshi1里面加载打勾图标  
  52.             $("#xianshi2").empty();  
  53.             $("#xianshi2").append("未被使用");//在di为xianshi2中加载“未被使用”这四个字  
  54.         }  
  55.            else   
  56.         {  
  57.             $("#xianshi1").empty();  
  58.             isClickOk=false;  
  59.             var txt1="<img src="+"'imgs/agree_no.gif'"+"/>"//引入打叉图标的路径  
  60.             $("#xianshi1").append(txt1);//在id为xianshi1里面加载打叉图标  
  61.             $("#xianshi2").empty();  
  62.             $("#xianshi2").append("已被使用");//在id为xianshi2里面加载“已被使用”四个字                 
  63.         }  
  64.     }  
  65. });  
  66. });  
  67.       
  68. });  
  69.   
  70. //添加信息点击保存的时候触发此函数  
  71. function add_ok(){        
  72.     $.messager.defaults={ok:"确定",cancel:"取消"};   
  73.     $.messager.confirm('Confirm''您确定增加?'function(r){//使用确定,取消的选择框  
  74.         if (r){  
  75.             $('#addForm').form('submit',{//引入Easyui的Form  
  76.                 url:"studentadd.action",//URL指向添加的Action  
  77.                 onSubmit: function(){  
  78.                     if(isClickOk==false){//当主键重复的时候先前就已经被设置为false,如果为false就不提交,显示提示框信息不能重复  
  79.                         $.messager.alert('操作提示''主键不能重复!','error');  
  80.                         return false;  
  81.                     }                 
  82.                     else if($('#addForm').form('validate')){//判断Easyui的Validate如果都没错误就同意提交  
  83.                         $.messager.alert('操作提示''添加信息成功!','info');  
  84.                         return true;  
  85.                     }else{//如果Easyui的Validate的验证有一个不完整就不提交  
  86.                         $.messager.alert('操作提示''信息填写不完整!','error');  
  87.                         return false;     
  88.                         }                                 
  89.                 }  
  90.             });  
  91.             $('#mydatagrid').datagrid({url:'studentallInfo.action'});//实现Datagrid重新刷新效果  
  92.             $('#addDlg').dialog('close');//关闭对话框  
  93.               }       
  94.     });   
  95. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值