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