1.1 说明:
实现了easyui的datagrid行编辑模式的CRUD
使用session存储数据变更
专注前端,抛弃了mybatis持久化
20170907
1.2 依赖环境:jar包
1.3 项目结构:
1.4 控制器:DataGridManagementInRowController.java
package com.cat.spring.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.springMyBatis.system.model.DataGridVO;
import com.springMyBatis.system.model.UserEasyUITutorial;
import com.springMyBatis.system.model.UserEasyUITutorialSorter;
@Controller
publicclassDataGridManagementInRowController {
@RequestMapping(value ="/DataGridManagementInRow", method = RequestMethod.GET)
public ModelAndViewindex(StringredirectURL,HttpServletRequestrequest){
ModelAndViewview=newModelAndView();
view.setViewName("/DataGridManagementInRow");
returnview;
}
privateHashMap<String, UserEasyUITutorial>GetUserTutorialMp() {
//人的ID从1开始,集合索引从1开始
HashMap<String,UserEasyUITutorial>mp =newHashMap<String, UserEasyUITutorial>();
for (inti = 0; i < 13;i++) {
UserEasyUITutorialobj=newUserEasyUITutorial();
Integerindex=i + 1;
Stringname="zhaohy"+index;
obj.setName(name);
obj.setPassword("2319474");
obj.setId(index);
//日期格式化
SimpleDateFormatdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
obj.setCreateddatetime(df.format(new Date()));
obj.setModifydatetime(df.format(new Date()));
mp.put(index.toString(),obj);
}
returnmp;
}
@RequestMapping(value ="/DataGridManagementInRow_Load", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> Load(DataGridVOdgVO, HttpServletRequestrequest) {
// Integer page, Integer rows,
// String sort, String order
//这里只使用名称过滤
Stringname=dgVO.getName();
Integerpage=dgVO.getPage();
Integerrows=dgVO.getRows();
Stringsort=dgVO.getSort();
Stringorder=dgVO.getOrder();
Objectobj=request.getSession().getAttribute("DataGridManagementInSession");
HashMap<String,UserEasyUITutorial>mp =null;
if (obj ==null) {
mp = GetUserTutorialMp();
request.getSession().setAttribute("DataGridManagementInSession",mp);
}else{
mp =(HashMap<String,UserEasyUITutorial>)request.getSession().getAttribute("DataGridManagementInSession");
}
Map<String,Object> result= newHashMap<String, Object>();
try {
if (page ==null) {
// Integer
page = 1;
}
if (rows ==null) {
// Integer
rows = 10;
}
List<UserEasyUITutorial>lst= GetList(mp,name);
List<UserEasyUITutorial>lstPaged=newArrayList<>();
//冒泡排序
intcounter =lst.size();
if (counter == 0) {
Integertotal=lst.size();
result.put("rows",lstPaged);
result.put("total",total);
returnresult;
}
for (inti = counter - 1;i > 0;i--) {
for (intj = 0; j < i; j++) {
UserEasyUITutorialsrc=lst.get(j);
UserEasyUITutorialtarget=lst.get(j + 1);
UserEasyUITutorialSorter.Exchange(src,target,sort, order);// "Name",
// "asc");
//显示排序后
System.out.println(src.getId() +"" + src.getName()+" "
+src.getPassword()+" "
+src.getCreateddatetime()+""
+src.getModifydatetime());
System.out.println(target.getId() +"" + target.getName()
+" " +target.getPassword()+" "
+target.getCreateddatetime()+""
+target.getModifydatetime());
}
}
for (inti = (page - 1) *rows;i < (page) *rows &&i < lst.size();i++) {
// Integer index = i + 1;
ObjectobjUserTutorial=lst.get(i);// mp.get(index.toString());
if (objUserTutorial !=null) {
lstPaged.add((UserEasyUITutorial)objUserTutorial);
}
}
// List<UserTutorial> list = userService.findAll(params);
Integertotal=lst.size();// userService.countTotal(params);
result.put("rows",lstPaged);
result.put("total",total);
}catch(Exceptione) {
// _logger.error("用户信息列表加载失败... {}",new Object[]{e});
result.put("errorMessage","用户信息列表加载失败");
}
returnresult;
}
@RequestMapping(value ="/DataGridManagementInRow_Save", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> Save(DataGridVOlpvo, HttpServletRequestrequest) {
Stringname=lpvo.getName();
Stringpassword=lpvo.getPassword();
Stringcreateddatetime=lpvo.getCreateddatetime();
Stringmodifydatetime=lpvo.getModifydatetime();
Stringid =lpvo.getId();
Objectobj=request.getSession().getAttribute("DataGridManagementInSession");
HashMap<String,UserEasyUITutorial>mp =null;
if (obj ==null) {
mp = GetUserTutorialMp();
}else{
mp =(HashMap<String,UserEasyUITutorial>)obj;
}
Map<String,Object> result= newHashMap<String, Object>();
try {
UserEasyUITutorialobjUser=newUserEasyUITutorial();
Integerindex;
if (id !=null) {
index = Integer.parseInt(id);
mp.remove(id);
}else{
intcounter =mp.size();
index =counter + 1;
}
objUser.setName(name);
objUser.setPassword(password);
objUser.setId(index);
objUser.setCreateddatetime(createddatetime);
objUser.setModifydatetime(modifydatetime);
mp.put(index.toString(),objUser);
request.getSession().removeAttribute("DataGridManagementInSession");
request.getSession().setAttribute("DataGridManagementInSession",mp);
result.put("flag","true");
result.put("Msg","保存成功!");
}catch(Exceptione) {
result.put("flag","false");
result.put("Msg","用户信息列表加载失败");
}
returnresult;
}
@RequestMapping(value ="/DataGridManagementInRow_Delete", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> Delete(Stringids,HttpServletRequestrequest) {
Objectobj=request.getSession().getAttribute("DataGridManagementInSession");
HashMap<String,UserEasyUITutorial>mp =null;
mp =(HashMap<String,UserEasyUITutorial>)obj;
Map<String,Object> result= newHashMap<String, Object>();
try {
String[]idArray=ids.split(",");
for (Stringid :idArray) {
mp.remove(id);
}
request.getSession().removeAttribute("DataGridManagementInSession");
request.getSession().setAttribute("DataGridManagementInSession",mp);
result.put("flag","true");
result.put("Msg","删除成功!");
}catch(Exceptione) {
result.put("flag","false");
result.put("Msg","删除失败!");
}
returnresult;
}
privateList<UserEasyUITutorial> GetList(
HashMap<String,UserEasyUITutorial>mp, Stringname){
List<UserEasyUITutorial>list=newArrayList<>();
Collectioncollection=mp.values();
Iteratoriterator=collection.iterator();
while (iterator.hasNext()) {
// System.out.println(iterator.next());
if (name !=null &&name.length() > 0&&name.trim().length()> 0) {
UserEasyUITutorialue =(UserEasyUITutorial)iterator.next();
if (ue.getName().contains(name)) {
list.add(CloneUserEasyUITutorial(ue));
}
}else{
list.add(CloneUserEasyUITutorial((UserEasyUITutorial)iterator
.next()));
}
}
returnlist;
}
private UserEasyUITutorialCloneUserEasyUITutorial(UserEasyUITutorialue) {
UserEasyUITutorialtarget=newUserEasyUITutorial();
BeanUtils.copyProperties(ue,target);
returntarget;
}
}
1.5 模型类:DataGridVO.java
package com.springMyBatis.system.model;
publicclassDataGridVO {
Integerpage;
Integerrows;
Stringsort;
Stringorder;
Stringname;
Stringpassword;
Stringcreateddatetime;
Stringmodifydatetime;
Stringid;
public String getId() {
returnid;
}
publicvoid setId(Stringid) {
this.id =id;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(Stringpassword) {
this.password =password;
}
public StringgetCreateddatetime() {
returncreateddatetime;
}
publicvoidsetCreateddatetime(Stringcreateddatetime) {
this.createddatetime =createddatetime;
}
public StringgetModifydatetime() {
returnmodifydatetime;
}
publicvoidsetModifydatetime(Stringmodifydatetime) {
this.modifydatetime =modifydatetime;
}
StringcreateddatetimeEnd;
StringcreateddatetimeStart;
StringmodifydatetimeEnd;
public Integer getPage() {
returnpage;
}
publicvoid setPage(Integerpage) {
this.page =page;
}
public Integer getRows() {
returnrows;
}
publicvoid setRows(Integerrows) {
this.rows =rows;
}
public String getSort() {
returnsort;
}
publicvoid setSort(Stringsort) {
this.sort =sort;
}
public String getOrder() {
returnorder;
}
publicvoid setOrder(Stringorder) {
this.order =order;
}
public String getName() {
returnname;
}
publicvoid setName(Stringname) {
this.name =name;
}
public StringgetCreateddatetimeEnd() {
returncreateddatetimeEnd;
}
publicvoidsetCreateddatetimeEnd(StringcreateddatetimeEnd) {
this.createddatetimeEnd=createddatetimeEnd;
}
public StringgetCreateddatetimeStart() {
returncreateddatetimeStart;
}
publicvoidsetCreateddatetimeStart(StringcreateddatetimeStart) {
this.createddatetimeStart=createddatetimeStart;
}
public StringgetModifydatetimeEnd() {
returnmodifydatetimeEnd;
}
publicvoidsetModifydatetimeEnd(StringmodifydatetimeEnd) {
this.modifydatetimeEnd=modifydatetimeEnd;
}
public StringgetModifydatetimeStart() {
returnmodifydatetimeStart;
}
publicvoidsetModifydatetimeStart(StringmodifydatetimeStart) {
this.modifydatetimeStart=modifydatetimeStart;
}
StringmodifydatetimeStart;
}
1.6 模型类:UserEasyUITutorial.java
package com.springMyBatis.system.model;
publicclassUserEasyUITutorial {
privateintid;
privateStringname;
publicint getId() {
returnid;
}
publicvoid setId(intid) {
this.id =id;
}
public String getName() {
returnname;
}
publicvoid setName(Stringname) {
this.name =name;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(Stringpassword) {
this.password =password;
}
private Stringpassword;
private Stringcreateddatetime;
public StringgetCreateddatetime() {
returncreateddatetime;
}
publicvoidsetCreateddatetime(Stringcreateddatetime) {
this.createddatetime =createddatetime;
}
public StringgetModifydatetime() {
returnmodifydatetime;
}
publicvoidsetModifydatetime(Stringmodifydatetime) {
this.modifydatetime =modifydatetime;
}
private Stringmodifydatetime;
}
1.7 前端jsp: DataGridManagementInRow.jsp
<%@ page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>EasyUI入门——创建EasyUI的DataGrid2</title>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<metahttp-equiv="cache-control"content="no-store,must-revalidate">
<metahttp-equiv="expires"content="0">
<!-- 引入JQuery -->
<scripttype="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.3.6/jquery.min.js"></script>
<!-- 引入EasyUI -->
<scripttype="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.3.6/jquery.easyui.min.js"></script>
<!-- 引入EasyUI的中文国际化js,让EasyUI支持中文 -->
<scripttype="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.3.6/locale/easyui-lang-zh_CN.js"></script>
<!-- 引入EasyUI的样式文件-->
<linkrel="stylesheet"
href="${pageContext.request.contextPath}/jquery-easyui-1.3.6/themes/default/easyui.css"
type="text/css"/>
<!-- 引入EasyUI的图标样式文件-->
<linkrel="stylesheet"
href="${pageContext.request.contextPath}/jquery-easyui-1.3.6/themes/icon.css"
type="text/css"/>
<styletype="text/css">
.tableForm {
}
.tableFormth {
text-align:right;
}
.tableFormtd input{
width:150px;
text-align:left;
}
</style>
<scripttype="text/javascript">
$(function() {
//url="get_users.php"
});
</script>
</head>
<bodyclass="easyui-layout">
<divregion="north"title="NorthTitle"style="height:100px;"></div>
<divregion="south"title="SouthTitle"split="true"
style="height:100px;"></div>
<divregion="west"split="true"title="West"style="width:200px;"></div>
<divregion="center"href="DGM.html"iconCls="icon-save"
title="center title"style="overflow:hidden;"></div>
</body>
</html>
1.8 前端html:DGM.html
<script type="text/javascript" charset="utf-8">
var sy = $.extend({}, sy);//定义全局对象
sy.serializeObject= function(form){//将表单元素序列化成对象
var o = {};
$.each(form.serializeArray(),function(index){
if (o[this['name']]) {
o[this['name']] = o[this['name']] + "," + this['value'];
}else{
o[this['name']] = this['value'];
}
});
return o;
};
$.extend($.fn.datagrid.defaults.editors,{
datetimebox: {
init: function(container,options) {
var editor = $('<input />').appendTo(container);
options.editable= false;
editor.datetimebox(options);
return editor;
},
getValue: function(target){
return $(target).datetimebox('getValue');
},
setValue: function(target,value) {
$(target).datetimebox('setValue', value);
},
resize: function(target,width) {
$(target).datetimebox('resize', width);
}
},
destroy: function(target){
$(target).datetimebox('destroy');
}
});
$.extend($.fn.datagrid.methods,{
addEditor: function(jq,param){
if(param instanceof Array){
$.each(param,function(index,item){
var e=$(jq).datagrid('getColumnOption',item.field);
e.editor=item.editor;
});
} else{
var e=$(jq).datagrid('getColumnOption',param.field);
e.editor=param.editor;
}
},
removeEditor: function(jq,param){
if(param instanceof Array){
$.each(param,function(index,item){
var e=$(jq).datagrid('getColumnOption',item);
e.editor={};
});
} else{
var e=$(jq).datagrid('getColumnOption',param);
e.editor={};
}
}
});
var datagrid;
varsy_admin_user_searchForm;
$(function() {
sy_admin_user_searchForm= $('#admin_user_searchForm').form();
sy_admin_user_editRow= undefined;
datagrid= $('#datagrid').datagrid({
url: '/EasyUITutorialNoPersistence/DataGridManagementInRow_Load',
title: '',
iconCls: 'icon-save',
pagination: true,
pageSize: 10,
pageList: [ 10, 20, 30, 40 ],
fit: true,
fitColumns: true,
nowrap: false,
border: false,
idField: 'id',
sortName: 'name',
sortOrder: 'desc',
columns: [ [ {
title: '编号',
field: 'id',
width: 100,
sortable: true,
checkbox: true
},{
title: '姓名',
field: 'name',
width: 100,
sortable: true,
editor: {type : 'validatebox',
options: {required : true}
}
},{
title: '密码',
field: 'password',
width: 100,
editor: {type : 'validatebox',
options: {required : true}
}
},{
title: '创建时间',
field: 'createddatetime',
width: 100,
editor: {type : 'datetimebox',
options: {required : true,showSeconds: true}
}
},{
title: '最后修改时间',
field: 'modifydatetime',
width: 100,
editor: {type : 'datetimebox',
options: {required : true,showSeconds: true}
}
}] ],
toolbar: [{text : '增加',
iconCls: 'icon-add',
handler: function(){
if (sy_admin_user_editRow!= undefined) {
datagrid.datagrid('endEdit',sy_admin_user_editRow);
}
if (sy_admin_user_editRow== undefined) {
datagrid.datagrid('addEditor',{
field:'password',
editor: {
type: 'validatebox',
options: {
required: true
}
}
});
datagrid.datagrid('insertRow',
{index: 0,
row: {
name: '请输入名称',
password : '请输入密码'
}
});
//var rows=datagrid.datagrid('getRows');
//console.info(rows.length);
datagrid.datagrid('beginEdit',0);//rows.length-1);
sy_admin_user_editRow= 0;
}
}
},
'-',
{ text : '删除',
iconCls: 'icon-remove',
handler: function(){
var rows =datagrid.datagrid('getSelections');
//getColumnOption
var field =datagrid.datagrid('getColumnOption','id');
console.info(field);
if (rows.length > 0) {
$.messager.confirm('请确认', '您确定要删除当前所有选择的项目么?', function(b){
if (b){
var ids=[];
for(var i=0;i<rows.length;i++)
{ids.push(rows[i].id)}
$.ajax({
type: "post",//发送方式
url: "/EasyUITutorialNoPersistence/DataGridManagementInRow_Delete",// 路径
data: {ids : ids.join(',')},
success: function(text){
//var obj = jQuery.parseJSON(text );
if (text.flag == "true") {
$.messager.show({msg: text.Msg,title : '提示'});
sy_admin_user_editRow= undefined;
datagrid.datagrid('load',sy.serializeObject(sy_admin_user_searchForm));
datagrid.datagrid('unselectAll');
}
if (text.flag == "false"){$.messager.show({msg : text.Msg,title : '提示'});}
}
});
}
});
}else{ $.messager.alert('提示','请选择要删除的记录!', 'error'); }
}
},
'-',
{ text : '修改',
iconCls: 'icon-edit',
handler: function(){
var rows =datagrid.datagrid('getSelections');
if (rows.length == 1) {
datagrid.datagrid('removeEditor','password');
//getRowIndex
if (sy_admin_user_editRow != undefined) {
datagrid.datagrid('endEdit',sy_admin_user_editRow);
}
if (sy_admin_user_editRow== undefined) {
var rowIndex =datagrid.datagrid('getRowIndex',rows[0]);
if (rowIndex == -1) {//翻页选中了
sy_admin_user_editRow= undefined;
}else{
sy_admin_user_editRow= rowIndex;
datagrid.datagrid('beginEdit',rowIndex);//rows.length-1);
}
datagrid.datagrid('unselectAll');
}
}else{ $.messager.show({ msg : '请选中一行编辑',title : '提示' }); }
}
},
'-',
{
text: '保存',
iconCls: 'icon-save',
handler: function(){
if(sy_admin_user_editRow!=undefined){
datagrid.datagrid('endEdit',sy_admin_user_editRow);
}
}
},'-',{
text: '取消编辑',
iconCls: 'icon-redo',
handler : function() {
sy_admin_user_editRow= undefined;
datagrid.datagrid('rejectChanges');
datagrid.datagrid('unselectAll');
}
},'-'],
onAfterEdit: function(rowIndex,rowData, changes) {
$.ajax({ type : "post",//发送方式
url: "/EasyUITutorialNoPersistence/DataGridManagementInRow_Save",// 路径
data: rowData,
success: function(text){
//var obj = jQuery.parseJSON(text );
if (text.flag == "true") {
$.messager.show({ msg : text.Msg,title : '提示' });
sy_admin_user_editRow= undefined;
datagrid.datagrid( 'load',
sy.serializeObject(sy_admin_user_searchForm));
}
if (text.flag == "false"){
$.messager.show({ msg : text.Msg,title : '提示' });
}
}
});
//console.info(rowData);
//console.info(changes);
//sy_admin_user_editRow = undefined;
//datagrid.datagrid('load',sy.serializeObject(sy_admin_user_searchForm));
},
onDblClickRow: function(rowIndex,rowData) {
if (sy_admin_user_editRow!= undefined) {
datagrid.datagrid('endEdit',sy_admin_user_editRow);
}
if (sy_admin_user_editRow== undefined) {
datagrid.datagrid('removeEditor','password');
datagrid.datagrid('beginEdit', rowIndex);//rows.length-1);
sy_admin_user_editRow= rowIndex;
}
}
});
});
sy_admin_user_search= function(){
datagrid.datagrid('load',sy.serializeObject(sy_admin_user_searchForm));
};
sy_admin_user_cleanSearch= function(){
//console.log(sy_admin_user_searchForm.serialize());
//console.log(sy_admin_user_searchForm.serializeArray());
datagrid.datagrid('load', {});
sy_admin_user_searchForm.find('input').val('');
};
</script>
<div class="easyui-layout"fit="true" border="false">
<div region="north" border="false"title="过滤" style="height: 110px; overflow: hidden;">
<form id="admin_user_searchForm">
<table class="tableForm datagrid-toolbar" style="width: 100%; height: 100%">
<tr>
<th>用户名</th>
<td><input name="name"style="width: 315px;" /></td>
</tr>
<tr>
<th>创建时间</th>
<td><input name="createddatetimeStart"
class="easyui-datetimebox" editable="false" style="width: 155px" />至<input
name="createddatetimeEnd" class="easyui-datetimebox"
editable="false" style="width: 155px" /></td>
</tr>
<tr>
<th>最后修改时间</th>
<td><input name="modifydatetimeStart"
class="easyui-datetimebox" editable="false" style="width: 155px" />至<input
name="modifydatetimeEnd" class="easyui-datetimebox"
editable="false" style="width: 155px" /><a
href="javascript:void(0);" class="easyui-linkbutton"
onclick="sy_admin_user_search();"plain='true'>查询</a><a
href="javascript:void(0);" class="easyui-linkbutton"
onClick="sy_admin_user_cleanSearch();"plain='true'>清空</a></td>
</tr>
</table>
</form>
</div>
<div region="center" border="false">
<table id="datagrid"></table>
</div>
</div>
1.9 运行效果:
测试网址:
http://localhost:8060/EasyUITutorialNoPersistence/DataGridManagementInRow