easyui可编辑表格 Datagrid

样式预览

Jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3     String path = request.getContextPath();
 4     String basePath = request.getScheme() + "://"
 5             + request.getServerName() + ":" + request.getServerPort()
 6             + path + "/";
 7 %>
 8 
 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11 <head>
12 <base href="<%=basePath%>">
13 
14 <script type="text/javascript"
15     src="easyui/jquery-easyui-v1.5/jquery.min.js"></script>
16 <script type="text/javascript"
17     src="easyui/jquery-easyui-v1.5/jquery.easyui.min.js"></script>
18 <link href="easyui/jquery-easyui-v1.5/themes/icon.css" rel="stylesheet"
19     type="text/css" />
20 <script type="text/javascript"
21     src="easyui/jquery-easyui-v1.5/locale/easyui-lang-zh_CN.js"></script>
22 <link href="easyui/jquery-easyui-v1.5/themes/default/easyui.css"
23     rel="stylesheet" type="text/css" />
24 <script type="text/javascript" src='${pageContext.request.contextPath}/js/newIndex.js'>
25     
26 </script>
27 </head>
28 
29 <body>
30     <table id='dg'></table>
31     <div id='tc' style="background-color: #EBEBEB"></div>
32     <table id='pc' style="300px" height="200px"></table>
33 <script type="text/javascript">
34 </script>
35 
36 </body>
37 </html>
Js文件 (newIndex.js)
  1 /**
  2  * 
  3  */
  4 
  5 $(function() {
  6     $('#dg').datagrid({
  7         url : 'UC/showAll.action',
  8         rownumbers : true,
  9         pagination : true,
 10         fitColumns:true,
 11         pageList : [ 5, 10, 15, 20 ],
 12         idField : 'id',
 13         columns : [ [ {
 14             field : 'ID',
 15             title : '账户ID',
 16             width : 100,
 17         }, {
 18             field : 'loginname',
 19             title : '登录名',
 20             width : 100,
 21             editor : {
 22                 type : "validatebox",
 23                 options : {
 24                     required : true,
 25                     validType:"loginName"
 26                 }
 27             }
 28         }, {
 29             field : 'PASSWORD',
 30             title : '密码',
 31             width : 100,
 32             align : 'right',
 33             editor : {
 34                 type : "validatebox",
 35                 options : {
 36                     required : true
 37                 }
 38             }
 39         }, {
 40             field : 'STATUS',
 41             title : '状态',
 42             width : 100,
 43             align : 'right',
 44             formatter: function(value,row,index){
 45                 if (row.status==1){
 46                     return "正常使用";
 47                 } else {
 48                     return "禁止使用";
 49                 }
 50             },
 51 
 52             editor : {
 53                 type: 'combobox',
 54                 options: {
 55                     panelHeight : 50,
 56                     url:'UC/allStatus.action',
 57                     valueField: 'id',
 58                     textField: 'name',
 59                     editable:false
 60                     
 61                 }
 62             }
 63         }, {
 64             field : 'createdate',
 65             title : '创建时间',
 66             width : 100,
 67             align : 'right',
 68         }, {
 69             field : 'username',
 70             title : '系统管理',
 71             width : 100,
 72             align : 'right',
 73             formatter: function(value,row,index){
 74                 if (row.username==1){
 75                     return "超级管理员";
 76                 } else if(row.username==2) {
 77                     return "普通管理员";
 78                 }else if(row.username==3){
 79                     return "普通用户";
 80                 }
 81             },
 82             editor : {
 83                 type: 'combobox',
 84                 options: {
 85                     panelHeight : 70,
 86                     url:'UC/allRoles.action',
 87                     valueField: 'id',
 88                     textField: 'name',
 89                     editable:false
 90                     
 91                 }
 92             }
 93         }] ],
 94         loadFilter : function(data) {
 95             var data_ = {
 96                 "rows" : data.attributes.rows,
 97                 "total" : data.obj.totalSize
 98             };
 99             return data_;
100 
101         }
102     });
103     var editBoxing = undefined;
104     $('#dg').datagrid({
105         toolbar : [ {
106             text : '新增',
107             iconCls : 'icon-edit',
108             handler : function() {
109                 if (editBoxing == undefined) {
110                     editBoxing = 0;
111                     $('#dg').datagrid("insertRow", {
112                         index : editBoxing, // 索引从0开始
113                         row : {
114                             loginname : '',
115                             PASSWORD : '',
116                             STATUS: '',
117                             username:'',
118                         }
119                     });
120                     $('#dg').datagrid('beginEdit', editBoxing);
121                 } else {
122                     $.messager.alert('警告', '尚有未编辑完成单元,请继续编辑', 'info');
123                 }
124 
125             }
126         }, '-', {
127             text : '保存',
128             iconCls : 'icon-save',
129             handler : function() {
130                 $('#dg').datagrid('endEdit', editBoxing);
131                 editBoxing = undefined;
132             }
133         }, '-', {
134             text : '删除',
135             iconCls : 'icon-remove',
136             handler : function() {
137                 var array = $('#dg').datagrid('getSelections');
138                 if (array.length >= 1) {
139                     var str = '';
140                     for (var i = 0; i < array.length; i++) {
141                         str += array[i].ID + " ";
142                     }
143                     $.post('UC/deleteUserById.action', {
144                         str : str
145                     }, function(data) {
146                         if (data.success == true) {
147                             $('#dg').datagrid('reload');
148                             $.messager.show({
149                                 title : '更新消息',
150                                 msg : '删除成功',
151                                 timeout : 3000
152                             });
153                         }
154                         $('#dg').datagrid('reload');
155                     });
156                 } else {
157                     $.messager.alert('警告', '请选择一条记录');
158                 }
159             }
160         }, '-', {
161             text : '取消编辑',
162             iconCls : 'icon-redo',
163             handler : function() {
164                 if (editBoxing == 0) {
165                     $('#dg').datagrid('deleteRow', editBoxing);
166                     editBoxing = undefined;
167                     $('#dg').datagrid('reload');
168                 } else {
169                     editBoxing = undefined;
170                     $('#dg').datagrid('reload');
171 
172                 }
173 
174             }
175         }, '-', {
176             text : '查看详细信息',
177             iconCls : 'icon-search',
178             handler : function() {
179                 var array = $('#dg').datagrid('getSelections');
180                 if(array.length>0){
181                     $('#pc').dialog({    
182                         title: '人员基本信息',    
183                          400,    
184                         height: 250,    
185                         closed: false,    
186                         cache: false,    
187                         content:"<div id='divdiv'></div>",
188                         
189                         modal: true ,
190                     });
191                     var cc=document.createElement("table");
192                     cc.setAttribute("id", "ttt");
193                     document.getElementById("divdiv").appendChild(cc);
194                     $('#ttt').propertygrid({
195                         url : '    UC/selectById.action',
196                         showGroup : true,
197                         scrollbarSize : 0,
198                         queryParams : {
199                             id : array[0].ID,
200                         },
201                         loadFilter : function(data) {
202                             var data_ = {
203                                 "rows" :[{"name":"账户","value":data.obj.id,},{"name":"登录名","value":data.obj.loginname},{"name":"密码","value":data.obj.password},
204                                          {"name":"状态","value":data.obj.status},{"name":"创建时间","value":data.obj.createdate},
205                                          {"name":"系统身份","value":data.obj.username}],
206         
207                             };
208                             return data_;
209 
210                         }
211                      
212                     });
213                 }else{
214                     $.messager.alert('警告', '请选择一条记录');
215                 }
216                     
217                     
218             }
219         }, '-', ],
220         onAfterEdit : function(index, row, changes) {
221             if (row.ID == undefined) {
222                 $.post('UC/addUser.action', {
223                     loginname : row.loginname,
224                     PASSWORD : row.PASSWORD,
225                     STATUS:row.STATUS,
226                     username:row.username,
227                 }, function(data) {
228                     if (data.success == true) {
229                         $.messager.show({
230                             title : '更新消息',
231                             msg : '新增成功',
232                             timeout : 3000,
233                         });
234                         $('#dg').datagrid('reload');
235                     } else {
236                         $.messager.alert('警告', '未完成新增');
237                     };
238 
239                 });
240                 $('#dg').datagrid('load');
241             } else {
242                 $.post('UC/updataById.action', {
243                     ID:row.ID,
244                     loginname : row.loginname,
245                     PASSWORD : row.PASSWORD,
246                     STATUS:row.STATUS,
247                     username:row.username,
248                 }, function(data) {
249                     if (data.success == true) {
250                         $.messager.show({
251                             title : '更新消息',
252                             msg : '修改成功',
253                             timeout : 3000
254                         });
255                         $('#dg').datagrid('reload');
256                     } else {
257                         $.messager.alert('警告', '修改失败');
258                     }
259                 });
260             }
261 
262         },
263         onDblClickCell : function(index, field, value) {
264             if (editBoxing == undefined) {
265                 editBoxing = index;
266                 $('#dg').datagrid('beginEdit', index);
267                 var ed = $(this).datagrid('getEditor', {
268                     index : index,
269                     field : field
270                 });
271                 $(ed.target).focus();
272             } else {
273                 $('#dg').datagrid('endEdit', editBoxing);
274                 editBoxing = index;
275                 $('#dg').datagrid('beginEdit', index);
276                 var ed = $(this).datagrid('getEditor', {
277                     index : index,
278                     field : field
279                 });
280                 $(ed.target).focus();
281             }
282         }
283     });
284 
285 });
286 $.extend($.fn.validatebox.defaults.rules, {
287      loginName: { 
288            validator: function (value, param) { 
289            return /^[u0391-uFFE5w]+$/.test(value); 
290            }, 
291            message: '登录名称只允许汉字、英文字母、数字及下划线。' 
292           }
293 });

Controller代码

  1 package com.user.controller;
  2 
  3 import java.util.ArrayList;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.springframework.beans.factory.annotation.Autowired;
  9 import org.springframework.beans.factory.annotation.Qualifier;
 10 import org.springframework.stereotype.Controller;
 11 import org.springframework.web.bind.annotation.RequestMapping;
 12 import org.springframework.web.bind.annotation.RequestMethod;
 13 import org.springframework.web.bind.annotation.ResponseBody;
 14 import org.springframework.web.servlet.ModelAndView;
 15 
 16 import DouUtils.MyDataResult;
 17 
 18 import com.AjaxJson;
 19 import com.DataResult;
 20 import com.UtilsHelper;
 21 import com.user.po.UserInf;
 22 import com.user.po.UserInfC;
 23 import com.user.seriver.UserSerives;
 24 
 25 @Controller
 26 @RequestMapping(value = "/UC")
 27 public class UserController {
 28     @Autowired
 29     @Qualifier("UserSerives")
 30     private UserSerives UserSerives;
 31 
 32     /**
 33      * 插入一个新管理员用户
 34      * 
 35      * @param UserInf
 36      * @return
 37      */
 38     @RequestMapping(value = "/addUser", method = RequestMethod.POST)
 39     @ResponseBody
 40      public AjaxJson addUser(UserInf UserInf) {
 41         try {
 42             AjaxJson json = new AjaxJson();
 43             UserInf.setCreatedate(UtilsHelper.getDateFormatTime());// 设置管理员创建时间
 44             UserSerives.addUser(UserInf);
 45             json.setSuccess(true);
 46             return json;
 47         } catch (Exception e) {
 48             // TODO Auto-generated catch block
 49             e.printStackTrace();
 50             AjaxJson json = new AjaxJson();
 51             json.setSuccess(false);
 52             return json;
 53 
 54         }
 55     }
 56 
 57     /**
 58      * 根据管理员loginname查询管理员全部信息
 59      */
 60     @RequestMapping(value = "/selectById", method = RequestMethod.POST)
 61     @ResponseBody
 62     public AjaxJson selectUserById(int id) {
 63             try {
 64                 UserInf UserInf = new UserInf();
 65                 UserInf = UserSerives.selectUserById(id);
 66                 if (UserInf != null) {
 67                     AjaxJson json=new AjaxJson();
 68                     json.setObj(UserInf);
 69                     json.setSuccess(true);
 70                     json.setMsg("查询成功");
 71                     return json;
 72                 } else {
 73                     AjaxJson json=new AjaxJson();
 74                     json.setMsg("查无此人");
 75                     json.setSuccess(false);
 76                     return json;
 77                 }
 78             } catch (Exception e) {
 79                 // TODO Auto-generated catch block
 80                 e.printStackTrace();
 81                 AjaxJson json=new AjaxJson();
 82                 json.setSuccess(false);
 83                 json.setMsg("系统异常");
 84                 return json;
 85             }
 86 
 87     }
 88 
 89     /**
 90      * 管理员信息修改
 91      */
 92     @RequestMapping(value = "/updataById", method = RequestMethod.POST)
 93     public @ResponseBody AjaxJson updateUserById(UserInf UserInf) {
 94         AjaxJson json = new AjaxJson();
 95         try {
 96             UserSerives.updateUserById(UserInf);
 97             json.setSuccess(true);
 98             return json;
 99 
100         } catch (Exception e) {
101             // TODO: handle exception
102             e.printStackTrace();
103             json.setSuccess(false);
104             return json;
105         }
106 
107     }
108     /**
109      * 展示全部学生信息
110      * @return  ArrayList<StudentInfo> 装满学生信息的集合
111      */
112     @ResponseBody
113     @RequestMapping(value = "/showAll", method = RequestMethod.POST)
114     public  AjaxJson show_all_student_info(String page,String rows){
115         AjaxJson json = new AjaxJson();
116         MyDataResult result1;
117         if(page==null||rows==null){
118             result1=new MyDataResult(1,10);
119         }else{
120             result1=new MyDataResult(Integer.parseInt(page), Integer.parseInt(rows));
121         }
122         List<Map<String, Object>> Users =UserSerives.selectAllUser(result1);
123         Map<String, Object> map = new HashMap<String, Object>();
124         map.put("rows", Users);
125         DataResult result=new DataResult();
126         result.setTotalSize(UserSerives.findUserCount());
127         json.setAttributes(map);
128         json.setSuccess(true);
129         json.setObj(result);
130         return json;
131         
132         
133     }
134 }

ServiceImpl

 1 package com.user.seriver.impl;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import javax.annotation.Resource;
 7 
 8 import org.springframework.stereotype.Service;
 9 
10 import DouUtils.MyDataResult;
11 
12 import com.user.mapper.UserInfMapper;
13 import com.user.po.UserInf;
14 import com.user.po.UserInfC;
15 import com.user.seriver.UserSerives;
16 @Service("UserSerives")
17 public class UserSerivesImpl implements UserSerives {
18     @Resource
19     private UserInfMapper UserInfMapper; 
20     //插入普通管理员
21     public void addUser(UserInf UserInf) {
22         // TODO Auto-generated method stub
23         UserInfMapper.insertUser(UserInf);
24     }
25     //根据管理员名称搜索管理员信息
26     @Override
27     public UserInf selectUserById(int id) {
28         // TODO Auto-generated method stub
29         return UserInfMapper.selectUserById(id);
30     }
31     //跟新管理员信息
32     @Override
33     public void updateUserById(UserInf UserInf) {
34         // TODO Auto-generated method stub
35          UserInfMapper.updateUserById(UserInf);
36     }
37     //删除管理员账号
38     @Override
39     public void deleteUserById(List<Integer> list) {
40          UserInfMapper.deleteUserById(list);
41         // TODO Auto-generated method stub
42         
43     }
44     //查询记录总数量
45     @Override
46     public int findUserCount() {
47         // TODO Auto-generated method stub
48         return UserInfMapper.findUserCount();
49     }
50     @Override
51     public List<Map<String, Object>> selectAllUser(MyDataResult DataResult) {
52         // TODO Auto-generated method stub
53         return UserInfMapper.selectAllUsers(DataResult);
54     }
55 
56 }

mapper代码

 1 package com.user.mapper;
 2 
 3 
 4 import java.util.List;
 5 import java.util.Map;
 6 
 7 import DouUtils.MyDataResult;
 8 
 9 import com.user.po.UserInf;
10 import com.user.po.UserInfC;
11 
12 public interface UserInfMapper {
13     //新增用户
14     public void insertUser(UserInf userInf) ;
15     //根据id准确查询
16     public UserInf selectUserById(int id);
17     //更新用户信息
18     public void updateUserById(UserInf UserInf);
19     //超级管理员可以删除用户
20     public void deleteUserById(List<Integer> list);
21     //查询管理员数量
22     public int findUserCount();
23     //查询全部管理员账号
24     public List<Map<String, Object>> selectAllUsers( MyDataResult DataResult );
25  
26 }

mapper.xml

  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.user.mapper.UserInfMapper">
  4 
  5     <resultMap type="com.user.po.UserInfC" id="UserMap">
  6         <collection property="array" javaType="ArrayList" ofType="com.user.po.UserInf">
  7             <id column="ID" property="id" />
  8             <result column="loginname" property="loginname" />
  9             <result column="STATUS" property="STATUS" />
 10             <result column="creatdate" property="createdate" />
 11             <result column="username" property="username" />
 12         </collection>
 13     </resultMap>
 14 
 15     <insert id="insertUser" parameterType="com.user.po.UserInf" >
 16         insert into user_inf
 17         <trim prefix="(" suffix=")" suffixOverrides=",">
 18             <if test="ID != null">
 19                 ID,
 20             </if>
 21             <if test="loginname != null">
 22                 loginname,
 23             </if>
 24             <if test="PASSWORD != null">
 25                 PASSWORD,
 26             </if>
 27             <if test="STATUS != null">
 28                 STATUS,
 29             </if>
 30             <if test="createdate != null">
 31                 createdate,
 32             </if>
 33             <if test="username != null">
 34                 username,
 35             </if>
 36         </trim>
 37         <trim prefix="values (" suffix=")" suffixOverrides=",">
 38             <if test="ID != null">
 39                 #{ID,jdbcType=INTEGER},
 40             </if>
 41             <if test="loginname != null">
 42                 #{loginname,jdbcType=VARCHAR},
 43             </if>
 44             <if test="PASSWORD != null">
 45                 #{PASSWORD,jdbcType=VARCHAR},
 46             </if>
 47             <if test="STATUS != null">
 48                 #{STATUS,jdbcType=INTEGER},
 49             </if>
 50             <if test="createdate != null">
 51                 #{createdate,jdbcType=VARCHAR},
 52             </if>
 53             <if test="username != null">
 54                 #{username,jdbcType=INTEGER},
 55             </if>
 56         </trim>
 57     </insert>
 58     <select id='selectUserById' parameterType="Integer" resultType="com.user.po.UserInf">
 59         select * from user_inf where ID=#{ID}
 60     </select>
 61 
 62     <select id='selectUsers' parameterType="Integer" resultMap="UserMap">
 63         select * from user_inf where STATUS=#{STATUS}
 64     </select>
 65 
 66     <update id="updateUserById" parameterType="com.user.po.UserInf" >
 67         update user_inf
 68         set
 69         loginname
 70          = #{loginname,jdbcType=VARCHAR},
 71         PASSWORD =#{PASSWORD,jdbcType=VARCHAR},
 72         STATUS = #{STATUS,jdbcType=INTEGER},
 73         username = #{username}
 74         where ID=#{ID}
 75     </update>
 76 
 77     <delete id="deleteUserById" parameterType="List">
 78 
 79         delete from user_inf
 80         <where>
 81             <if test="list!=null and list.size>0">
 82                 <foreach collection="list" open=" and id in(" close=")"
 83                     item="id" separator=",">
 84                     #{id}
 85                 </foreach>
 86             </if>
 87         </where>
 88     </delete>
 89     
 90     <select id="selectAllUsers"  parameterType="DouUtils.MyDataResult"
 91         resultType="Map">
 92         select * from user_inf  limit #{startLine},#{pageSize}
 93     </select>
 94 
 95     <select id="findUser" parameterType="com.user.po.UserInf"
 96         resultType="com.user.po.UserInf">
 97         select * from user_inf where ID=#{ID}
 98     </select>
 99     <select id="findUserCount" resultType="Integer">
100         select count(*) from
101         user_inf
102     </select>
103 
104 </mapper>

MyDataResult 代码

 1 public class MyDataResult {
 2     /**
 3      * 记录开始的条数
 4      */
 5     private int startLine;
 6     /**
 7      * 每页记录数
 8      */
 9     private int pageSize;
10     /**
11      * 当前页
12      */
13     private int currentPage;
14     /**
15      * 总记录数
16      */
17     private int totalSize;
18     /**
19      * 总页数
20      */
21     private int totalPage;
22 
23     public MyDataResult() {
24         super();
25         // TODO Auto-generated constructor stub
26     }
27 
28     public MyDataResult(int currentPage,int pageSize) {
29         super();
30         this.pageSize = pageSize;
31         this.currentPage = currentPage;
32         this.startLine = (this.currentPage - 1) * pageSize;
33     }
34 
35     public int getStartLine() {
36         return startLine;
37     }
38 
39     public void setStartLine(int startLine) {
40         this.startLine = startLine;
41     }
42 
43     public int getPageSize() {
44         return pageSize;
45     }
46 
47     public void setPageSize(int pageSize) {
48         this.pageSize = pageSize;
49     }
50 
51     public int getCurrentPage() {
52         return currentPage;
53     }
54 
55     public void setCurrentPage(int currentPage) {
56         this.currentPage = currentPage;
57     }
58 
59     public int getTotalSize() {
60         return totalSize;
61     }
62 
63     public void setTotalSize(int totalSize) {
64         this.totalSize = totalSize;
65     }
66 
67     public int getTotalPage() {
68         return totalPage;
69     }
70 
71     public void setTotalPage(int totalPage) {
72         this.totalPage = totalPage;
73     }
74 
75 }

AjaxJson 源码

 1 public class AjaxJson {
 2 
 3     private boolean success = false;// 是否成功
 4     private String msg = "操作失败";// 提示信息
 5     private Object obj = null;// 其他信息
 6     private Map<String, Object> attributes;// 其他参数
 7 
 8     public Map<String, Object> getAttributes() {
 9         return attributes;
10     }
11 
12     public void setAttributes(Map<String, Object> attributes) {
13         this.attributes = attributes;
14     }
15 
16     public String getMsg() {
17         return msg;
18     }
19 
20     public void setMsg(String msg) {
21         this.msg = msg;
22     }
23 
24     public Object getObj() {
25         return obj;
26     }
27 
28     public void setObj(Object obj) {
29         this.obj = obj;
30     }
31 
32     public boolean isSuccess() {
33         return success;
34     }
35 
36     public void setSuccess(boolean success) {
37         this.success = success;
38     }
39 
40     public String getJsonStr() {
41         
42         JSONObject obj = new JSONObject();
43         obj.put("success", this.isSuccess());
44         obj.put("msg", this.getMsg());
45         obj.put("obj", this.obj);
46         obj.put("attributes", this.attributes);
47         return obj.toString();
48     }
49 }

DataResult 源码(和上面MyDataRusult几乎一样,在Controller 中有使用,可修改为一个,代码自己该改动)

 1 public class DataResult {
 2     /**
 3      * 记录开始的条数
 4      */
 5     private int startLine;
 6     /**
 7      * 每页记录数
 8      */
 9     private int pageSize = 10;
10     /**
11      * 当前页
12      */
13     private int currentPage = 1;
14     /**
15      * 总记录数
16      */
17     private int totalSize;
18     /**
19      * 总页数
20      */
21     private int totalPage;
22     public int getStartLine() {
23         return startLine;
24     }
25     public void setStartLine(int startLine) {
26         this.startLine = startLine;
27     }
28     public int getPageSize() {
29         return pageSize;
30     }
31     public void setPageSize(int pageSize) {
32         this.pageSize = pageSize;
33     }
34     public int getCurrentPage() {
35         return currentPage;
36     }
37     public void setCurrentPage(int currentPage) {
38         this.currentPage = currentPage;
39     }
40     public int getTotalSize() {
41         return totalSize;
42     }
43     public void setTotalSize(int totalSize) {
44         this.totalSize = totalSize;
45     }
46     public int getTotalPage() {
47         return totalPage;
48     }
49     public void setTotalPage(int totalPage) {
50         this.totalPage = totalPage;
51     }
52     
53     
54     
55 }

原文地址:https://www.cnblogs.com/fudou/p/7990921.html