項目中用到了jQuery的jqGrid表格控件,功能還算強大。主要是在封裝json資料的時候比較麻煩,先來看grid要求的json資料格式:
{"total":1,"page":1,"records":10,"rows":[{"id":1,"cell":["字段1","字段2",.....]},{[id":2,"cell":["字段1","字段2",.....]}]}
total:總頁數,page:目前頁碼,records:每頁顯示記錄數,rows為記錄集合。如果要使用分頁的話,将這些參數設為背景分頁類的分頁參數即可。
先來看前台頁面代碼,
<link rel="stylesheet" type="text/css" media="screen" href="${ctx}/themes/basic/grid.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" mce_href="${ctx}/themes/basic/grid.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<mce:script src="${ctx}/js/jquery.js" mce_src="${ctx}/js/jquery.js"type="text/javascript"></mce:script>
<mce:script src="${ctx}/js/jqgrid/jquery.jqGrid.js" mce_src="${ctx}/js/jqgrid/jquery.jqGrid.js" type="text/javascript"></mce:script>
<mce:script type="text/javascript"><!--
// We use a document ready jquery function.
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
// the url parameter tells from where to get the data from server
// adding ?nd='+new Date().getTime() prevent IE caching
url:'terminal-users!loadByFilters',
// datatype parameter defines the format of data returned from the server
// in this case we use a JSON data
datatype: "json",
// colNames parameter is a array in which we describe the names
// in the columns. This is the text that apper in the head of the grid.
colNames:['使用者代碼','使用者名', '部門','安全域','綁定終端','操作'],
// colModel array describes the model of the column.
// name is the name of the column,
// index is the name passed to the server to sort data
// note that we can pass here nubers too.
// width is the width of the column
// align is the align of the column (default is left)
// sortable defines if this column can be sorted (default true)
colModel:[
{name:'userId',index:'userId', width:80},
//grid獲得資料隻跟你背景放入cell中的順序要關系
{name:'userName',index:'userName',
//index為排序參數名
width:80,formatter:'showlink',formatoptions:{baseLinkUrl:'terminal-users!input.action',showAction:'',idName:"entityId"}},
//字段加入baseLinkUrl屬性後就支援超連接配接了
{name:'departmentName',index:'departmentInfo.departmentId', width:80},
{name:'domainName',index:'securityDomain.domainId',sortable:false, width:150},
//不需要排序的話将字段的sortable置為false
{name:'computerName',sortable:false, width:150},
{name:'option',index:'option', width:120,sortable:false,align:'center'}
],
// pager parameter define that we want to use a pager bar
// in this case this must be a valid html element.
// note that the pager can have a position where you want
pager: jQuery('#pager'),
// rowNum parameter describes how many records we want to
// view in the grid. We use this in example.php to return
// the needed data.
rowNum:10,
// rowList parameter construct a select box element in the pager
//in wich we can change the number of the visible rows
rowList:[10,20,30],
// path to mage location needed for the grid
imgpath: 'themes/basic/images',
// sortname sets the initial sorting column. Can be a name or number.
// this parameter is added to the url
sortname: 'userId',//預設排序字段
//viewrecords defines the view the total records from the query in the pager
//bar. The related tag is: records in xml or json definitions.
viewrecords: true,
//sets the sorting order. Default is asc. This parameter is added to the url
sortorder: "asc",//預設排序方式
weight:600,
height:200,
multiselect:true,
prmNames:{rows:"page.pageSize",page:"page.pageNo",sort:"page.orderBy",order:"page.order"}
//我項目中使用的是struts2,并用page類作為分頁,設定這
//些參數後struts2會代我們攔截到page中以完成分頁和排
//序。如果不用struts2這些參數可以在request中取得,名
//字分别為rows,page,sort,order。
});
});
// --></mce:script>
<!-- the grid definition in html is a table tag with class 'scroll' -->
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<!-- pager definition. class scroll tels that we want to use the same theme as grid -->
<div id="pager" class="scroll" style="text-align:center;" mce_style="text-align:center;"></div>
再來看背景,我們需要一個用于分頁的類,貼一下我用的分頁類
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* 與具體ORM實作無關的分頁參數及查詢結果封裝.
*
* @param <T> Page中記錄的類型.
* @author calvin
*/
public class Page<T> {
// 公共變量
public static final String ASC = "asc";
public static final String DESC = "desc";
public static final int MIN_PAGESIZE = 5;
public static final int MAX_PAGESIZE = 200;
//分頁參數
protected int pageNo = 1;
protected int pageSize = MIN_PAGESIZE;
protected String orderBy = null;
protected String order = null;
protected boolean autoCount = true;
//傳回結果
protected List<T> result = Collections.emptyList();
protected int totalCount = -1;
// 構造函數
public Page() {
super();
}
public Page(final int pageSize) {
setPageSize(pageSize);
}
public Page(final int pageSize, final boolean autoCount) {
setPageSize(pageSize);
this.autoCount = autoCount;
}
//查詢參數函數
/**
* 獲得目前頁的頁号,序号從1開始,預設為1.
*/
public int getPageNo() {
return pageNo;
}
/**
* 設定目前頁的頁号,序号從1開始,低于1時自動調整為1.
*/
public void setPageNo(final int pageNo) {
this.pageNo = pageNo;
if (pageNo < 1) {
this.pageNo = 1;
}
}
/**
* 獲得每頁的記錄數量,預設為10.
*/
public int getPageSize() {
return pageSize;
}
/**
* 設定每頁的記錄數量,超出MIN_PAGESIZE與MAX_PAGESIZE範圍時會自動調整.
*/
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
if (pageSize < MIN_PAGESIZE) {
this.pageSize = MIN_PAGESIZE;
}
if (pageSize > MAX_PAGESIZE) {
this.pageSize = MAX_PAGESIZE;
}
}
/**
* 根據pageNo和pageSize計算目前頁第一條記錄在總結果集中的位置,序号從0開始.
*/
public int getFirst() {
return ((pageNo - 1) * pageSize);
}
/**
* 獲得排序字段,無預設值.多個排序字段時用','分隔,僅在Criterion查詢時有效.
*/
public String getOrderBy() {
return orderBy;
}
/**
* 設定排序字段.多個排序字段時用','分隔.僅在Criterion查詢時有效.
*/
public void setOrderBy(final String orderBy) {
this.orderBy = orderBy;
}
/**
* 是否已設定排序字段,僅在Criterion查詢時有效.
*/
public boolean isOrderBySetted() {
return StringUtils.isNotBlank(orderBy);
}
/**
* 獲得排序方向,預設為asc,僅在Criterion查詢時有效.
*
* @param order 可選值為desc或asc,多個排序字段時用','分隔.
*/
public String getOrder() {
return order;
}
/**
* 設定排序方式向,僅在Criterion查詢時有效.
*
* @param order 可選值為desc或asc,多個排序字段時用','分隔.
*/
public void setOrder(final String order) {
//檢查order字元串的合法值
String[] orders = StringUtils.split(StringUtils.lowerCase(order), ',');
for (String orderStr : orders) {
if (!StringUtils.equals(DESC, orderStr) && !StringUtils.equals(ASC, orderStr))
throw new IllegalArgumentException("排序方向" + orderStr + "不是合法值");
}
this.order = StringUtils.lowerCase(order);
}
/**
* 查詢對象時是否自動另外執行count查詢擷取總記錄數,預設為false,僅在Criterion查詢時有效.
*/
public boolean isAutoCount() {
return autoCount;
}
/**
* 查詢對象時是否自動另外執行count查詢擷取總記錄數,僅在Criterion查詢時有效.
*/
public void setAutoCount(final boolean autoCount) {
this.autoCount = autoCount;
}
// 查詢結果函數
/**
* 取得頁内的記錄清單.
*/
public List<T> getResult() {
return result;
}
public void setResult(final List<T> result) {
this.result = result;
}
/**
* 取得總記錄數,預設值為-1.
*/
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(final int totalCount) {
this.totalCount = totalCount;
}
/**
* 根據pageSize與totalCount計算總頁數,預設值為-1.
*/
public int getTotalPages() {
if (totalCount < 0)
return -1;
int count = totalCount / pageSize;
if (totalCount % pageSize > 0) {
count++;
}
return count;
}
/**
* 是否還有下一頁.
*/
public boolean isHasNext() {
return (pageNo + 1 <= getTotalPages());
}
/**
* 取得下頁的頁号,序号從1開始.
*/
public int getNextPage() {
if (isHasNext())
return pageNo + 1;
else
return pageNo;
}
/**
* 是否還有上一頁.
*/
public boolean isHasPre() {
return (pageNo - 1 >= 1);
}
/**
* 取得上頁的頁号,序号從1開始.
*/
public int getPrePage() {
if (isHasPre())
return pageNo - 1;
else
return pageNo;
}
}
jqGrid是一ajax的方式請求資料的,背景接收到請求時先将分頁參數儲存在page中,然後通過page分頁查詢,最後再将資料儲存為json格式傳回給Grid就大功告成了。
Page<TerminalUsers> pageTerminalUsers = search(page);//查詢獲得分頁後的資料
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>(); // 記錄
for (TerminalUsers terminalUser : result) {
int userId = terminalUser.getUserId();
String userName = terminalUser.getUserName();
String departmentName = terminalUser.getDepartmentInfo()
.getDepartmentName();
String domainNames = terminalUser.getDomainNames();
String computerNames = terminalUser.getComputerNames();
// 将需要顯示的資料放入一對象數組中
Object[] cell = {
userId,
userName,
departmentName,
domainNames,
computerNames,
"<a href="/" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" mce_href="/" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" "terminal-users!input.action?entityId="
+ userId
+ "/">修改</a>"
+ " "
+ "<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" mce_href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" οnclick=/"jqGridDel('#list','terminal-users!delete.action',"
+ userId + ")/" title = '删除' >删除</a>"
+ " "
+ "<a href =/"terminal-users!copy.action?copyId="
+ userId + "/">複制</a>" };
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", userId);
map.put("cell", cell);
rows.add(map);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", pageTerminalUsers.getTotalPages());
map.put("page", pageTerminalUsers.getPageNo());
map.put("records", pageTerminalUsers.getPageSize());
map.put("rows", rows);
// 産生JSON對象
JSONObject json = JSONObject.fromObject(map);
時間比較緊,寫的很簡單,有問題歡迎大家提出來。