以前曾经写过一个类似的,但是看了留言说数据怎么怎么传不对,那是因为如果你仅仅只会依葫芦画瓢,那不对是正常的,好了,我今天就再写一个,你依葫芦画瓢一定可以画出来的玩意。呵呵。OK,言归正传先从实体开始说,我这里做例子,依然用最简单的来。
@Entity
@Table(name = "t_fieldcolumn")

public class FieldColumn
{
@Id()
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String value;
private String id;
public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getValue()
{
return value;
}

public void setValue(String value)
{
this.value = value;
}

public Long getId()
{
return id;
}

public void setId(Long id)
{
this.id = id;
}
}
实体类的定义完成后,接着生成相应的service包括接口IFieldColumnService和其实现FieldColumnService
我只贴接口,具体实现嘛,自己去弄吧,嘻嘻

public interface IFieldColumnService extends EntityDao<FieldColumn, String>
{
public Page getAllFieldColumnList(int start,int limit,String sort,String dir,String name);
List<FieldColumn> getFilterList();
int getFilterCount();
public void addFieldColumn(FieldColumn field);
public void updateFieldColumn(FieldColumn filed);
public void getFieldColumnById(Long id);
public void deleteFieldColumn(Long id);
}
现在到Action了,关于struts2我就不多说了,现在已经很普及了,这里我强调的一点就是,我和原先的做法一样,还是将数据保存在一个名叫result.jsp中的jsonString变量中,有问题可以参见我原来的那篇文章,
@Controller

@Results(
{
@Result(name = "field", location = "/WEB-INF/page/field.jsp", type = "dispatcher"),
@Result(name = "success", location = "/WEB-INF/page/result.jsp", type = "dispatcher"),
@Result(name = "fail", location = "/index.jsp", type = "dispatcher")
})

public class FieldColumnAction extends BaseActionSupport
{

private static final long serialVersionUID = 1L;
@Autowired
@Qualifier("fieldColumnJdbcService")
private IFieldColumnService fieldColumnService;
private int limit=20;
private int start=1;
private String dir="";
private String sort="";
private String fieldId="";
private String jsonString="";
private String delData="";
private String fieldName = "";
private String fieldValue = "";
private String filterName = "";

/** *//**
* 查询功能
* @return
*/
@Action("/getFieldList")
public String getFieldColumnList()

{

Page page = new Page();
page = fieldColumnService.getAllFieldColumnList(start, limit, sort, dir, filterName);
if(page.getTotalCount()!=0)

{
List<FieldColumn> result = (List<FieldColumn>)page.getResult();
StringBuilder sb = new StringBuilder("{success:true,totalCount:");

sb.append(page.getTotalCount());

sb.append(",results:");

sb.append(FlexJsonUtils.getJsonString(result, null,

new String[]
{ "class" }, null));

sb.append("}");

jsonString = sb.toString();
}
else

{
jsonString = "{success:true,totalCount:0,results:[]}";
}
return SUCCESS;
}
}

/** *//**
* 进入管理页面
* @return
*/
@Action("/fieldcolumn")
public String getFieldIndex()

{
return "field";
}

/** *//**
* 根据field id 获取详细内容
* @return
*/
@Action("/getField")
public String getFieldInfo()

{
FieldColumn field = new FieldColumn();
field = fieldColumnService.get(fieldId);

if(field!=null)

{
StringBuilder sb = new StringBuilder();
sb.append("{success:true,");
sb.append("result:");

sb.append(FlexJsonUtils.getJsonString(field, null, new String[]
{"class"}, null));
sb.append("}");
jsonString = sb.toString();
}
else

{
jsonString="{success:false,msg:'load faild!'}";
}
return SUCCESS;
}

/** *//**
* 添加字段
* @return
*/
@Action("/addField")
public String addField()

{

FieldColumn field = new FieldColumn();
field.setName(fieldName);
field.setValue(fieldValue);
fieldColumnService.save(field);
jsonString="{success:true,msg:'add success!'}";
return SUCCESS;
}

/** *//**
* 获取类别名称
* @return
*/
@Action("/getFieldNameList")
public String getFieldNameList()

{
List<FieldColumn> result = new ArrayList<FieldColumn>();
FieldColumn fc = new FieldColumn();
fc.setName("All Field Results");
fc.setValue("");
fc.setId("");
result.add(fc);
result.addAll(fieldColumnService.getFilterList());
int total = fieldColumnService.getFilterCount()+1;

jsonString = "{success:true,totalCount:"+total+",results:"+FlexJsonUtils.getJsonString(result, null,new String[]
{ "class","id","value" }, null)+"}";
return SUCCESS;
}

/** *//**
* 更新功能
* @return
*/
@Action("/updateField")
public String updateField()

{

FieldColumn field = new FieldColumn();
field = fieldColumnService.get(fieldId);
if(!fieldName.equals(""))

{
field.setName(fieldName);
}
field.setValue(fieldValue);
fieldColumnService.merge(field);
jsonString="{success:true,msg:'update success!'}";
return SUCCESS;
}

/** *//**
* 删除功能
* @return
*/
@Action("/delField")
public String delField()

{

if(delData.indexOf(",")<0)

{
fieldColumnService.delete(delData.trim());
}
else

{
String[] ids = delData.split(",");
for(int i=0;i<ids.length;i++)

{
fieldColumnService.delete(ids[i].trim());
}
}
jsonString="{success:true,msg:'delete success!'}";
return SUCCESS;
}

public int getLimit()
{
return limit;
}


public void setLimit(int limit)
{
this.limit = limit;
}


public int getStart()
{
return start;
}


public void setStart(int start)
{
this.start = start;
}


public String getDir()
{
return dir;
}


public void setDir(String dir)
{
this.dir = dir;
}


public String getSort()
{
return sort;
}


public void setSort(String sort)
{
this.sort = sort;
}


public String getFieldId()
{
return fieldId;
}


public void setFieldId(String fieldId)
{
this.fieldId = fieldId;
}

public String getJsonString()
{
return jsonString;
}

public void setJsonString(String jsonString)
{
this.jsonString = jsonString;
}


public String getDelData()
{
return delData;
}

public void setDelData(String delData)
{
this.delData = delData;
}

public String getFieldName()
{
return fieldName;
}

public void setFieldName(String fieldName)
{
this.fieldName = fieldName;
}

public String getFieldValue()
{
return fieldValue;
}

public void setFieldValue(String fieldValue)
{
this.fieldValue = fieldValue;
}

public String getFilterName()
{
return filterName;
}

public void setFilterName(String filterName)
{
this.filterName = filterName;
}
}
如果你们对json的封装感到疑惑,请看我的flexJson那篇文章,我就是用哪个工具进行数据的json格式化的,呵呵,好了,现在到最前面了,那么首先在一个JSP页面中要把ext相关的文件都要引入

<%
@ page language="java" pageEncoding="UTF-8"%>

<%
@include file="/common/page/taglibs.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>FieldColumn</title>
<link rel="stylesheet" type="text/css" href="${ctx}/resource/ext/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/resource/css/field/tasks.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/resource/css/field/yeoougrid.css" /> <!--这个是自定义表格的css文件,其实通用的就够了-->
<link rel="stylesheet" type="text/css" href="${ctx}/resource/css/field/msg.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/resource/css/field/RowEditor.css" /><!--由于我设置了双击行能进行相应字段的更新操作,所以这个必须引入-->
<script type="text/javascript" src="${ctx}/common/scripts/ext/ext-base.js"></script>
<script type="text/javascript" src="${ctx}/common/scripts/ext/ext-all.js"></script>
<script type="text/javascript" src="${ctx}/common/scripts/util/JsonUtil.js"></script>
<script type="text/javascript" src="${ctx}/common/scripts/util/RowEditor.js"></script><!--由于我设置了双击行能进行相应字段的更新操作,所以这个必须引入-->
<script type="text/javascript" src="${ctx}/common/scripts/util/ExtendFormat.js"></script>
<script type="text/javascript" src="${ctx}/common/scripts/util/Ext.ux.plugins.js"></script><!--同上,是grid的插件,这个当然也是需要的-->
<script type="text/javascript" src="${ctx}/resource/scripts/field.js"></script><!--这个就是我们要写的文件了-->
</head>
<body>
</body>
</html>
我们现在就进入js文件中

/**//**
* Field Column Manager
* @author kensin
*/
var searchName="";

Ext.onReady(function()
{
Ext.BLANK_IMAGE_URL = './resource/ext/resources/images/default/s.gif';
Ext.QuickTips.init();
var id = 1;
var contentPanel, fpanel;//添加,更新的面板
var objectGrid;//表格组件
var selectRecord;//选择的记录
var objectStore;//数据仓库组件
var cbsm;//行组件
var actions;//添加,更新的动作
var tabPanel;
var dsFieldName;
var currentValue="";

initView();//载入视图
});
var pageSize = 50;
var addWin,updWin;//窗体
//载入视图方法

function initView()
{

new Ext.Viewport(
{
layout:'border',
items:initGrid()//将表格在视图中展现
});
}
//初始化视图方法

function initGrid()
{
//面板中会操作的对象属性
var idName = new Array('fieldName','fieldValue');
//对象的解析器

var roleReader = new Ext.data.JsonReader(
{
totalProperty: 'totalCount',
root: 'results',
successProperty:'success',
idProperty:'id',
//映射关系
fields: [

{name: 'id', type: 'string',mapping:'id'},

{name: 'name', type: 'string',mapping:'name'},

{name: 'value', type: 'string',mapping:'value'}
]
});
//下拉列表仓库

dsFieldName = new Ext.data.Store(
{

proxy: new Ext.data.HttpProxy(
{
url:'./getFieldNameList.do'
}),

reader: new Ext.data.JsonReader(
{
root: 'results',
totalProperty: 'totalCount',
successProperty:'success'
}, [

{name: 'name', mapping: 'name'}
])
});
//表格数据仓库

objectStore = new Ext.data.GroupingStore(
{
reader:roleReader,//以此方式来解析数据
proxy:new Ext.data.HttpProxy //请求并返回数据({url: './getFieldList.do',method:'POST'}),
remoteSort:true,
groupField:'name',//以name进行group by

sortInfo:
{},
//当双击行时对更新操作进行监听,并将当前值和修改值显示给用户,以便确认更新

listeners:
{

'update': function(thiz, record, operation)
{
var member = thiz.getAt(thiz.indexOf(record)).data;

if(operation == Ext.data.Record.EDIT)
{
Ext.MessageBox.show

(
{title:'<Strong>Modify Record</Strong>',
msg:'Are you sure want to modify this record? <br>Current Value:'+currentValue+'<br>New Value:'+member.value,
width:350,
height:100,
buttons:Ext.MessageBox.YESNO,

fn:function(btn)
{

if (btn == "yes")
{
//确认则更新 Ext.Ajax.request({
url: './updateField.do',//更新请求的URL
method:'post',

params:
{
fieldId:member.id,
fieldName:member.name,
fieldValue:member.value},

success:function(response, opts)
{
Ext.Msg.alert('Success', 'You have modified the current record');
thiz.commitChanges();
//更新完毕后显示最新的数据 objectStore.load({

params:
{
filterName:searchName,
start: objectGrid.getBottomToolbar().cursor,
limit: pageSize
}
});},

failure:function(response, opts)
{
Ext.Msg.alert('Faild','Update Faild');}
});
}
}
});
}
}
}
});
//初始化显示数据

objectStore.load(
{

params:
{
start: 0,
filterName:searchName,
limit: pageSize
}
});

var rn = new Ext.grid.RowNumberer();
//设置双击可进行更新的属性

var editor = new Ext.ux.grid.RowEditor(
{
saveText: 'Update',
cancelText:'Cancel',

listeners:
{


beforeedit:function(rowedit,index)
{
var m = objectGrid.getSelectionModel().getSelections();
currentValue = m[0].get('value');
}
}

});
cbsm = new Ext.grid.CheckboxSelectionModel();

var rn = new Ext.grid.RowNumberer();
//表格组件

objectGrid = new Ext.grid.GridPanel(
{
loadMask: true,
ds: objectStore,
columns: [
rn, //行号列
cbsm, //CheckBox选择列

{id:'id',header: 'fieldId', hidden:true, hideable:false, sortable: true,
dataIndex: 'id'},

{header: 'Field Name', hidden:true,fixed:false,hideable:false, sortable: true,
dataIndex: 'name'},

{header: 'Field Text', fixed:false,hideable:true, sortable: true,editor:
{xtype: 'textfield',allowBlank: false },
dataIndex: 'value'}
],
sm: cbsm,
plugins:[editor],//将双击可修插件定义

view: new Ext.grid.GroupingView(
{
forceFit: true,
showGroupName: false,
enableNoGroups: true,
hideGroupedColumn: false,

groupTextTpl: '
{text} (
{[values.rs.length]}
{[values.rs.length > 1 ? "rows" : "rows"]})'
}),
//表格最下栏显示信息

bbar: new Ext.PagingToolbar(
{
pageSize: pageSize,
store: objectStore,
displayInfo: true,

displayMsg: 'View
{0}-
{1} row / Total
{2} rows',
refreshText:'Refresh',
emptyMsg: "No data"
}),
//按钮

tbar: [
{
text: 'Add Field',
tooltip: 'Add a new field',
iconCls: 'add',

handler: function()
{
var tempName = Ext.get("filterName").dom.value;
addItem(idName,tempName);
}

},'-',
{
text: 'Update',
tooltip: 'Update field information',
iconCls: 'option',

handler: function()
{
updateItem(idName,objectGrid.getBottomToolbar().cursor);//objectGrid.getBottomToolbar().cursor当前记录
}
}

, '-',
{
text: 'Delete',
tooltip: 'Delete field information',
iconCls: 'remove',

handler: function()
{
delItem(objectGrid.getBottomToolbar().cursor);
}

},'-','Filter:',
{
xtype: 'combo',//下拉列表框
fieldLabel:'Filter',
store: dsFieldName,
displayField:'name',
hiddenName:'filterName',
valueField: 'name',
typeAhead: true,
readOnly:false,
loadingText: 'loading
',
width: 170,
hideTrigger:false,
minChars:1,
forceSelection:true,
triggerAction: 'all',

listeners:
{

'select':function(arg)
{//当值改变时出发查询方法把结果展示在表格中
searchName = Ext.get("filterName").dom.value;

objectStore.on('beforeload', function(thiz)
{

Ext.apply(thiz.baseParams,
{start: 0,
filterName:searchName,
limit: pageSize});
});

objectStore.load(
{

params:
{
start: 0,
filterName:searchName,
limit: pageSize
}
});
}
}

},

'-',
{
text: 'Home',
tooltip: 'Go back to the home page',
iconCls: 'application-go',
handler: function()

{
var strURL;
strURL="./homepage.do";
window.open(strURL,"_self",'');
}
}

,
{
xtype:"tbfill"
},

{
text: 'Logout',
tooltip: 'Logout',
iconCls: 'remove',
handler: function()

{
var strURL;
strURL="./logout.do";
window.open(strURL,'_self','');
}
}
],
frame: true,
title:'CMDB Interface',
region: 'center',
height: 150,
autoWidth: true,
animCollapse: false,
trackMouseOver: true
});
return objectGrid;
}
//创建更新窗体

function comCreate(idName,actions,start)
{
var attributePanel;

attributePanel = new Ext.Panel(
{
id: 'attrP',
layout: 'form',
bodyStyle: 'padding:10px',
autoScroll: true,

defaults:
{
xtype: 'textfield',
width: 250,
allowBlank: false,
anchor: '95%'
},

items: [
{
fieldLabel: 'Parent',
name: idName[0],
id: idName[0] ,
readOnly:true

},
{
fieldLabel: 'Enter New Value',
name: idName[1],
id: idName[1]
}]
});


fpanel = new Ext.FormPanel(
{
region: 'center',
bodyStyle: 'padding:5px',
fileUpload: true,
collapsible: true,//显示展开/收缩按钮
items: [attributePanel],

buttons: [
{
text: 'Update Value',

handler: function()
{
update(fpanel,start,attributePanel.findById(idName[1]).getValue());
}

},
{
text: 'Reset',

handler: function()
{
reset(fpanel,idName);
}

},
{
text: 'Cancel',

handler: function()
{
cancel();
}
}]
});
roleUpdateAjax(fpanel,actions,idName);
}
//创建添加窗体

function comAddCreate(idName,actions,start,parent)
{
var attributePanel;

attributePanel = new Ext.Panel(
{
id: 'attrP',
layout: 'form',
bodyStyle: 'padding:10px',
autoScroll: false,

defaults:
{
width: 100,
allowBlank: false,
anchor: '90%'
},

items: [
{
xtype: 'textfield',
fieldLabel: 'Parent',
name: idName[0],
id: idName[0],
readOnly:true

},
{
xtype: 'textfield',
fieldLabel: 'Enter New Value',
name: idName[1],
id: idName[1]
}]
});


fpanel = new Ext.FormPanel(
{
region: 'center',
bodyStyle: 'padding:5px',
fileUpload: false,
collapsible: false,//显示展开/收缩按钮
items: [attributePanel],

buttons: [
{
text: 'Add Value',

handler: function()
{
save(fpanel,start);
}

},
{
text: 'Reset',

handler: function()
{
reset(fpanel,idName);
}

},
{
text: 'Cancel',

handler: function()
{
cancel();
}
}]
});
fpanel.findById(idName[0]).setValue(parent);
}

//获取id为Id的FieldColumn信息

function roleUpdateAjax(fpanel,Id,idName)
{

Ext.Ajax.request(
{
url: './getField.do',
method: 'POST',

params:
{fieldId:Id},

success: function(result, request)
{
initUpdateRole(result,fpanel,idName);
},

failure: function(result, request)
{
Ext.MessageBox.alert('Load faild','Load field information faild!');
window.close();
}
});
}
//将获取的数据显示在更新窗体中

function initUpdateRole(result,fpanel,idName)
{
var fieldColumn = doJSON(result.responseText);

if (fieldColumn.success == true)
{
currentValue =fieldColumn.result.value;
fpanel.findById(idName[0]).setValue(fieldColumn.result.name);
fpanel.findById(idName[1]).setValue(fieldColumn.result.value);
}

else
{
Ext.MessageBox.alert('Load faild','Load field information faild!');
}
}



//弹出添加窗体

function addItem(idName,parent)
{
addWin = Ext.getCmp('addW');
id = 1;

if (!addWin)
{
comAddCreate(idName,'add',0,parent);

addWin = new Ext.Window(
{
title: 'Add Field',
id: 'addW',
closable: true,
width: 420,
height: 200,
modal: true,
layout: 'fit',
items: [fpanel]
});
}
addWin.show();
}
//弹出更新窗体

function updateItem(idName,start)
{
id = 1;
selectRecord = objectGrid.getSelectionModel().getSelected();

if (!selectRecord)
{
Ext.MessageBox.alert('Update', 'Please select a field!');
}

else
{

if (cbsm.getCount() == 1)
{
updWin = Ext.getCmp('updW');
comCreate(idName,selectRecord.get('id'),start);


if (!updWin)
{

updWin = new Ext.Window(
{
title: 'Update information',
id: 'updW',
closable: true,
width: 420,
height: 200,
plain: true,
modal: true,
layout: 'fit',
items: [fpanel]
});
}
updWin.show();
updWin.doLayout();
}

else
{
Ext.MessageBox.alert('Tip', 'Please select a field!');
}
}
}
//删除操作

function delItem(start)
{
selectRecord = objectGrid.getSelectionModel().getSelected();

if (!selectRecord)
{
Ext.MessageBox.alert('Delete Operation', 'Please select a field!');
}

else
{
var member = objectGrid.getSelectionModel().getSelections();
var value = member[0].get('value');
Ext.MessageBox.show

(
{title:'<Strong>Delete</Strong>',
msg:'Are you sure want to delete '+value+'?',
width:350,
height:80,
buttons:Ext.MessageBox.YESNO,

fn:function(btn)
{

if (btn == "yes")
{
var m = objectGrid.getSelectionModel().getSelections();
var jsonData = "";

for (var i = 0; i < m.length; i++)
{
var ss = m[i].get('id');

if (i === 0)
{
jsonData = jsonData + ss;
}

else
{
jsonData = jsonData + "," + ss;
}
objectStore.remove(m[i]);
}
delRoleAjax(start, jsonData);
}
}});
}
}//删除请求(在后台执行删除操作,并返回处理结果)

function delRoleAjax(start,jsonData)
{

Ext.Ajax.request(
{

url: './delField.do',
method: 'POST',

params:
{
delData: jsonData
},

success: function(result, request)
{
var returnJosn = doJSON(result.responseText);
if(returnJosn.success==true)

{
Ext.MessageBox.alert('Success', 'You have deleted a record!');
}
else

{
Ext.MessageBox.alert('Fail', 'You have not deleted a record!');

objectStore.load(
{

params:
{
filterName:searchName,
start: start,
limit: pageSize
}
});
}
},

failure: function(result, request)
{
Ext.MessageBox.alert('Delete Operation', 'Delete Faild!');

objectStore.load(
{

params:
{
filterName:searchName,
start: start,
limit: pageSize,
delData: jsonData
}
});
}
});
}
//更新操作
function update(fpanel,start,newValue)


{
var urlPost;
var paramsPost;
var tijiao = false;
urlPost = './updateField.do';

paramsPost =
{
fieldId: selectRecord.get('id')
};
Ext.MessageBox.show

(
{title:'<Strong>Modify Record</Strong>',
msg:'Are you sure want to modify this record? <br>Current Value:'+currentValue+'<br>New Value:'+newValue,
width:350,
height:100,
buttons:Ext.MessageBox.YESNO,

fn:function(btn)
{

if (btn == "yes")
{

if (fpanel.form.isValid())
{
this.disabled = true;

fpanel.getForm().submit(
{
url: urlPost,
method: 'post',
params: paramsPost,
waitTitle: 'Waitting information',
waitMsg: 'Data is submitting now please wait
',

failure: function(fpanel, action)
{
var returnJosn = action.result;
Ext.MessageBox.alert('save faild',returnJosn.msg);
this.disabled = false;
},

success: function(fpanel, action)
{
var returnJosn = action.result;

if (returnJosn.success === true)
{
Ext.MessageBox.alert('Success', 'you have modified the current record');

if (updWin)
{
updWin.close();
updWin = '';
}

objectStore.load(
{

params:
{
filterName:searchName,
start: start,
limit: pageSize
}
});
}

else
{
Ext.MessageBox.alert('save faild',returnJosn.msg);
this.disabled = false;
}
}
});
}

else
{
Ext.Msg.alert('Info', 'Please fill in the complete re-submit!');
}
}
}});
}
//添加操作

function save(fpanel,start)
{
var urlPost;
var paramsPost;

if (addWin)
{
urlPost = './addField.do';

paramsPost =
{
};
}
else

if (updWin)
{
urlPost = './updateField.do';

paramsPost =
{
fieldId: selectRecord.get('id')
};
}

else
{
Ext.Msg.alert('Message', 'Wrong Params!');
window.close();
}
//提交数据

if (fpanel.form.isValid())
{
this.disabled = true;

fpanel.getForm().submit(
{
url: urlPost,
method: 'post',
params: paramsPost,
waitTitle: 'Waitting information',
waitMsg: 'Data is submitting now please wait
',

failure: function(fpanel, action)
{
var returnJosn = action.result;
Ext.MessageBox.alert('save faild',returnJosn.msg);
this.disabled = false;
},

success: function(fpanel, action)
{
var returnJosn = action.result;

if (returnJosn.success === true)
{
Ext.MessageBox.alert('Success', 'you have added a new Record');

if (addWin)
{
addWin.close();
addWin = '';
}

if (updWin)
{
updWin.close();
updWin = '';
}

objectStore.load(
{

params:
{
filterName:searchName,
start: start,
limit: pageSize
}
});
}

else
{
Ext.MessageBox.alert('save faild',returnJosn.msg);
this.disabled = false;
}
}
});
}

else
{
Ext.Msg.alert('Info', 'Please fill in the complete re-submit!');
}
}

//重置操作

function reset(fpanel,idName)
{
fpanel.form.reset();
}
//退出

function cancel()
{
addWin = Ext.getCmp('addW');
updWin = Ext.getCmp('updW');

if (addWin)
{
addWin.close();
addWin='';
}

if (updWin)
{
updWin.close();
updWin='';
}
}

