[size=medium][b]最近用easyui的datagrid,此datagrid具有增删改查,满足基本的使用:[/b][/size]
1.jsp代码(对页面的初始化操作):
2.处理逻辑的TestAction类:
3.查询数据的QueryDao(如果大数据量,建议使用缓存):
以上就是如何基本使用easyui的datagrid...
1.jsp代码(对页面的初始化操作):
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<title>ComboBox - jQuery EasyUI Demo</title>
<%
String path = request.getContextPath();
%>
<link rel="stylesheet" type="text/css" href="<%=path %>/jquery_ui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/jquery_ui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/jquery_ui/ui.css">
<script type="text/javascript" src="<%=path %>/jquery_ui/jquery-1.6.min.js"></script>
<script type="text/javascript" src="<%=path %>/jquery_ui/jquery.easyui.min.js"></script>
<script>
$(function(){
var lastIndex;
$('#test').datagrid({
title:'My DataGrid',
iconCls:'icon-save',
width:800,
height:"auto",
nowrap: false,
striped: true,
collapsible:true,
url:'TestAction!getGridInfo.action',
idField:'id',
singleSelect:true,
fitColumns: true,
frozenColumns:[[
{field:'ck',checkbox:true},
{title:'编号',field:'id',width:80,sortable:true}
]],
columns:[[
{title:'基本信息',colspan:2},
{
field:'tel',
title:'移动电话',
width:100,
align:'center',
rowspan:2,
editor: {
type: 'numberbox',
options:{
required: true,
validType: "length[11,11]"
}
}
}
],[
{
field:'name',
title:'姓名',
width:120,
editor:'text'
},
{field:'address',title:'地址',width:220,rowspan:2,editor:'text'}
]],
pagination:true,
toolbar:[{
id:'btnadd',
text:'Add',
iconCls:'icon-add',
handler:function(){
$('#btnsave').linkbutton('enable');
alert('add')
}
},{
id:'btncut',
text:'Cut',
iconCls:'icon-cut',
handler:function(){
$('#btnsave').linkbutton('enable');
alert('cut')
}
},'-',{
id:'btnsave',
text:'Save',
disabled:true,
iconCls:'icon-save',
handler:function(){
$('#btnsave').linkbutton('disable');
alert('save')
}
}],
onClickRow: function(rowindex){
$('#test').datagrid('endEdit', lastIndex);
$('#test').datagrid('beginEdit', rowindex);
var ed = $('#test').datagrid('getEditors', rowindex);
for (var i = 0; i < ed.length; i++){
var e = ed[i];
$(e.target).bind("keyup",function(event){
if (event.which == 13){
$('#test').datagrid('endEdit', rowindex);
}
});
}
lastIndex = rowindex;
},
onAfterEdit: function(rowIndex, rowData){
$.ajax({
url: "<%=request.getContextPath()%>/TestAction!updateGrid.action",
data: "name="+encodeURIComponent(rowData.name)+"&address="+encodeURIComponent(rowData.address)+"&tel="+encodeURIComponent(rowData.tel)+"&id="+rowData.id,
cache:false,
async : true
})
}
});
var p = $('#test').datagrid('getPager');
$(p).pagination({
pageSize:10,
pageList:[10,20,50],
beforePageText: '第',
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条',
onBeforeRefresh:function(){
$("#test").datagrid("reload");
}
});
});
function search(value){
var p = $('#test').datagrid('getPager');
$(p).pagination({
pageNumber: 1
});
var queryParams = $('#test').datagrid('options').queryParams;
queryParams.name=value;
$('#test').datagrid("reload");
}
</script>
<style type="text/css">
.demo-info{
background:#FFFEE6;
color:#8F5700;
padding:12px;
}
.demo-tip{
width:24px;
height:16px;
float:left;
}
</style>
</head>
<body>
<h2>Complex DataGrid</h2>
<div class="demo-info">
<div class="demo-tip icon-tip"></div>
<div>Click the button to do actions with datagrid.</div>
</div>
<input class='easyui-searchbox' prompt='请输入姓名进行搜索' style='width:798px' searcher='search'/>
<table id="test"></table>
</body>
</html>
2.处理逻辑的TestAction类:
public class TestAction extends ActionSupport{
private int rows;
private int page;
private long total;
private QueryDao dao = new QueryDao();
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void getGridInfo(){
HttpServletRequest request = ServletActionContext.getRequest();
List<Grid> list = new ArrayList<Grid>();
String name = request.getParameter("name");
if(!("".equals(name) || name == null)){
//根据名称进行模糊查询,并初始化查询出来的数据的页数和行数
name = name.trim();
list = dao.getGridByName(name, page, rows);
total = dao.getSize();
}else{
total = dao.getTotal();
list=dao.getGridData(page ,rows);
}
Map<String,Object> jsonMap = new HashMap<String,Object>();
jsonMap.put("total", total);
jsonMap.put("rows", list);
JSONObject json=new JSONObject();
json=JSONObject.fromObject(jsonMap);
try {
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
PrintWriter pw=ServletActionContext.getResponse().getWriter();
pw.println(json.toString());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateGrid(){
String id=(String)ServletActionContext.getRequest().getParameter("id");
String name=(String)ServletActionContext.getRequest().getParameter("name");
String address=(String)ServletActionContext.getRequest().getParameter("address");
String tel=(String)ServletActionContext.getRequest().getParameter("tel");
String hql="update Grid g set g.name=?,g.address=?,g.tel=? where g.id=?";
try
{
DataAccess.createPersister().saveOrUpdateBySqlString(hql,new Object[]{name,address,tel,id});
dao.updateGridCache(id);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
3.查询数据的QueryDao(如果大数据量,建议使用缓存):
public class QueryDao{
private long size;
private int initPage;
public int getInitPage() {
return initPage;
}
public long getSize() {
return size;
}
/**
* 查询出所有的grid数据,便于进行大数据量的模糊查询
* @return
*/
public List<Grid> getAllGrid(){
String hql = "from Grid";
try
{
Query query = DataAccess.createQuery();
@SuppressWarnings("unchecked")
List<Grid> gridResult = query.queryByHqlString(hql);
return gridResult;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return new ArrayList<Grid>();
}
public List<Grid> getGridData(int page , int row){
//Cache cache = CacheManager.getInstance().getCache("grid");
List<Grid> list = (List<Grid>)getAllGrid();
return spliList(list, page, row);
}
public Long getTotal(){
String countHql = "select count(*) from Grid";
try
{
Query query = DataAccess.createQuery();
List countList = query.queryByHqlString(countHql);
long total = (Long)countList.get(0);
return total;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return 0L;
}
public Grid getGridById(String id){
String hql = "from Grid where id=?";
try
{
Query query = DataAccess.createQuery();
List countList = query.queryByHqlString(hql,new Object[]{id});
return (Grid)countList.get(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return new Grid();
}
/**
* 查询包含此数据名的数据
* @param name
* @param total
* @return
*/
public List<Grid> getGridByName(String name,int page, int rows){
List<Grid> gridList = new ArrayList<Grid>();
Cache cache = CacheManager.getInstance().getCache("grid");
List<Grid> list = (List<Grid>)cache.getValue();
for(int i = 0, len = list.size(); i < len; i++){
Grid grid = (Grid) list.get(i);
if(grid.getName().contains(name)){
gridList.add(grid);
}
}
size = gridList.size();
return spliList(gridList, page, rows);
}
/**
* 对list进行分页
* @param list
* @param page
* @param rows
* @return
*/
public List spliList(List list, int page, int rows){
List grid = new ArrayList();
int a = (page - 1) * rows;
int b = a + rows;
for(int i = a; i < b; i++){
try {
grid.add(list.get(i));
} catch (IndexOutOfBoundsException e) {
return grid;
}
}
return grid;
}
public void updateGridCache(String id){
Cache cache = CacheManager.getInstance().getCache("grid");
List<Grid> list = (List<Grid>)cache.getValue();
for (int i = 0, len = list.size(); i < len; i++) {
Grid grid = list.get(i);
if(id.equals(grid.getId())){
Grid updateGrid = getGridById(id);
list.remove(i);
list.add(i, updateGrid);
cache.setValue(list);
return;
}
}
}
}
以上就是如何基本使用easyui的datagrid...