jqGrid與Struts2集成

由於公司項目須要,在Hibernate+Struts2的環境下,研究了一下如何使用jqGrid。javascript

說實在的,Struts2+jqGrid不是一個很好的組合。由於jqGrid中不少功能,基本上都使用的是AJAX的訪問方式,而且,你們都知道,jqGrid須要的數據,要麼是XML格式的,要麼是JSON格式。(固然,我說的是通常狀況,其實jqGrid還支持本地數據,以及xml字符串、json字符串之類的)css

而Struts2已經把Action的返回作了很好的封裝了。通常的狀況下,最好不要經過Action的Execute方法去訪問HttpServletResponse對象。可是要使用qGrid,就必須在execute方法中調用response,組裝須要的xml或者json格式的數據,並返回到客戶端。html

怎麼說呢,感受比較怪異。另外,估計是我對struts2的json-plugin還不太熟悉,也不會用這個玩意,因此總是以爲程序的結構很怪異!java

直白的說,jqGrid提供了一個很方便的數據顯示外殼,可是具體的全部動做,仍是要本身來實現。記住:jqGrid是基於服務器端處理的,也就是說,一切的查詢、排序、分頁等功能,都須要你在服務器端去本身實現。(我準備在下一篇文章中詳細說一下jqGrid的簡單查詢——只經過一個字段過濾的查詢動做,這是jqGrid默認的查詢!)jquery

下面是個人一個例子,隨便寫在這裏供之後查閱(寫給同事看的,你們別較真!):數據庫

 

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>json

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">服務器

 <head>
 <title>jqgrid demo in Struts2</title>
 <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
 <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
 <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.multiselect.css" />
 <style>
  html, body {
   margin: 0;   /* Remove body margin/padding */
   padding: 0;
   overflow: hidden; /* Remove scroll bars on browser window */ 
      font-size: 75%;
  }
  .ui-tabs-nav li {position: relative;}
  .ui-tabs-selected a span {padding-right: 10px;}
  .ui-tabs-close {display: none;position: absolute;top: 3px;right: 0px;z-index: 800;width: 16px;height: 14px;font-size: 10px; font-style: normal;cursor: pointer;}
  .ui-tabs-selected .ui-tabs-close {display: block;}
  .ui-layout-west .ui-jqgrid tr.jqgrow td { border-bottom: 0px none;}
  .ui-datepicker {z-index:1200;}
 </style>框架

 <script src="js/jquery.js" type="text/javascript"></script>
 <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
 <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>jsp

 <script src="js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
 <script src="js/jquery.layout.js" type="text/javascript"></script>
 <script src="js/jquery.tablednd.js" type="text/javascript"></script>
 <script src="js/jquery.contextmenu.js" type="text/javascript"></script>
 <script src="js/ui.multiselect.js" type="text/javascript"></script>

 <script type="text/javascript">
  $(document).ready(function(){
   $("#jsonmap").jqGrid({       
       url:'queryAllUsers.action',
    datatype: "json",
    postData: {depId: 1},
      colNames:['ID','姓名', '登陸名', '部門ID','是否可用'],
       colModel:[
         {name:'id',index:'id', width:90},
        {name:'userName',index:'usrName', width:110},
          {name:'loginName',index:'loginName', width:100},
        {name:'dpCode',index:'dpCode', width:80, align:"right"},
        {name:'isUsed',index:'isUsed', width:80, align:"right"} 
       ],
       rowNum:10,
       rowList:[10,20,30],
       pager: '#pjmap',
       sortname: 'id',
       viewrecords: true,
       sortorder: "desc",
    jsonReader: {
     repeatitems : false,
     id: "0"
    },
    caption: "部門人員信息"
   }).navGrid('#pjmap',{edit:false,add:false,del:false});
  });
 
 </script>
 
 </head>
 <body>
  <table id="jsonmap" class="scroll" cellpadding="0" cellspacing="0"></table>
  <div id="pjmap" class="scroll" style="text-align:center;"></div>
  <!--
   關於JQGrid的使用說明
   1.jsp文件說明
    請注意本文件中第一行的contentType="text/html; charset=UTF-8"這一句,這是解決中文問題的,很是重要。
    請注意本文件中的<!DOCTYPE這一行代碼,以及HTML行的代碼,這是有xmlns驗證的,若是沒有這兩句,顯示出來的Table的樣式很是難看!!
    jquery-ui的字體大小與jqgrid字體大小不一致,故須要在頁面上在加上一段style來指定頁面上文字大小。
    請注意,須要使用jqGrid,必須的js代碼主要包括jquery以及jqGrid.min,另外就是jqGrid的語言包。其它的js代碼是可選的,根據使用jqGrid的不一樣功能有所不一樣。
    請注意,須要使用的css文件,jquery-ui-1.7.1.custom.css以及ui.jqgrid.css是必須的。其它的css是可選的,根據使用jqGrid的不一樣功能有所不一樣。
    最後請注意,導航條,必定只能是一個DIV,不能是Table。好比本例子中的pjmap。

   2.主方法jqGrid參數說明(上面例子中的參數,其它參數說明見doc目錄下的文檔)
    $("#jsonmap").jqGrid({              //此處請注意#jsonmap,這是須要顯示的Table的對象ID
     url:'queryAllUsers.action',     //請求的URL地址
     datatype: "json",               //服務器返回的數據類型,經常使用的是xml和json兩種
     postData: {depId: 1},           //提交的其餘參數,好比查詢條件。這裏depId是參數名稱,值能夠經過$(#ID).val();來獲取
     colNames:['ID','姓名', '登陸名', '部門ID','是否可用'],  //表頭顯示的列名稱
     colModel:[                      //這個屬性是爲每個列設置屬性的。很是重要
      {name:'id',index:'id', width:90},   //具體的列屬性,name必須有。index屬性設置鼠標點擊相應的表頭的時候,排序的字段。這裏還能夠設置列是否可見,是否可編輯.....詳細請參考文檔
      {name:'userName',index:'usrName', width:110},
      {name:'loginName',index:'loginName', width:100},
      {name:'dpCode',index:'dpCode', width:80, align:"right"},
      {name:'isUsed',index:'isUsed', width:80, align:"right"} 
     ],
     rowNum:10,                      //默認的每頁顯示記錄條數
     rowList:[10,20,30],             //可供用戶選擇的每頁顯示記錄條數。
     pager: '#pjmap',    //pjmap是導航條對應的Div標籤的ID,注意必定是DIV,不是Table
     sortname: 'id',     //默認的查詢排序字段
     viewrecords: true,    //定義是否在導航條上顯示總的記錄數
     sortorder: "desc",    //默認的排序規則
     jsonReader: {     //jsonReader定義了一些指望返回數據的結構信息,經過修改這些參數定義,咱們能夠實現本身的Json數據格式,不用遵守JQGrid的默認規則(不熟悉的狀況下,不建議修改)
      repeatitems : false,  //告訴JqGrid,返回的數據的標籤是不是可重複的。This element tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name. This is the name from colModel or the name described with the jsonmap option in colModel。
      id: "0"      //每行數據的惟一標識。能夠設置爲空字符串或者一個數字。在這個例子中,表示每行數據的ID是返回數據的第一個字段。
     },
     caption: "部門人員信息"   //顯示錶格的表名稱
    }).navGrid('#pjmap',{edit:false,add:false,del:false});  //navGrid是比較重要和經常使用的一個jqGrid方法。主要用來指示導航條的一些動做,包括設置整個Grid的編輯、刪除、查詢、導航的一些屬性信息。詳細參考文檔Navgiation章節。
    //更多更詳細的參數以及說明,請參考本項目doc/JQuery & Plugin/jqGrid Document.doc.

   3.服務器Struts的Action方法說明
    假設使用Struts 2.0做爲Web層框架,那麼咱們在Struts中的execute方法中,須要直接返回查詢結果。
    首先,Action須要獲取jqGrid上傳的一些參數,如下幾個參數是jgGrid必須包括的參數:(能夠在prmNames參數中設置這些參數的值爲null,則不會在調用url的使用上傳這些參數,固然,也能夠自定義一些其餘名字的參數。)
     page :指示須要查詢第幾頁的數據。
     rows :指示每頁顯示的記錄條數。
     sidx :指示查詢排序的條件,這是一個字符串,多是數據庫表字段或者是POJO對象的屬性名。這須要程序來處理。
     sord :指示查詢排序的方式,可能的值是ASC和DESC
     _search :用來指示是不是查詢,值是true或者false。可是我測試了一下,好比這個例子中,剛開始訪問頁面的時候,_search=false。這個時候不論是點擊哪個表頭排序,執行的動做,後臺接收到的都是false。若是點擊一下Navigation工具條最左邊的查詢按鈕,執行一次查詢動做,這個時候,_search就變成true了。包括以後,再去點擊顯示錶頭進行排序,其_search的結果都是true了。有點怪異!!!
     nd :暫時沒搞懂什麼意思?
     npage:暫時沒搞懂什麼意思?
    其次,Action返回的xml或者json數據,有一些數據須要包含,主要包括
     page:當前是第幾頁數據
     total:總共有多少頁數據
     records:總的記錄條數

    服務器端代碼示例:(execute方法或者是Struts.xml中配置的某些方法名稱)
     
     //假設查詢結果是一個封裝了查詢List的POJO對象,注意,調用方法的參數,具備分頁功能,分頁參數,能夠經過Struts2的Action屬性自動獲取
     UserSearchTo to  = this.service.findTo( page, rows, sidx, sord);
     
     //封裝成JSON對象返回,這裏使用了json-lib包,要注意,這個包要用到幾個其餘的jar包,主要包括commons-lang 2.四、commons-beanutils 1.7.0、commons-collections 3.二、commons-logging 1.1.1以及ezmorph 1.0.6
     HttpServletResponse response = ServletActionContext.getResponse();
     response.setContentType("text/json; charset=UTF-8");  //處理中文問題的必須的代碼
     PrintWriter out = response.getWriter();
     
     JSONObject obj = new JSONObject();
     obj.put("page", to.getPage());    //當前頁
     obj.put("total",to.getTotal());    //總頁數
     obj.put("records",to.getRecords());   //總記錄數
     
     JSONArray lineitemArray = new JSONArray();
     for(User u:to.getUserList()){
      JSONObject o = new JSONObject();
      o.put("id", u.getId());
      o.put("userName", u.getUsrName());
      o.put("loginName", u.getLoginName());
      o.put("dpCode", u.getDpCode());
      o.put("isUsed", u.getIsUsed());
      lineitemArray.add(o);
     }
     obj.put("rows", lineitemArray);    //具體的Table顯示內容
     out.print(obj.toString());

 

     服務器端代碼示例:struts.xml配置片斷       <action name="queryAllUser" class="brandAction" method="queryAllBrand">         <result name="success">/viewBrandGrid.jsp</result>         <result name="error">/viewBrandGrid.jsp</result>         <result name="input">/viewBrandGrid.jsp</result>         <interceptor-ref name="defaultStack"></interceptor-ref>       </action>  --> </body></html>

相關文章
相關標籤/搜索