Struts 2.0ではJSONを使ってDWRとEXTを結合します.


Struts 2.0ではJSONを使ってDWRとEXTを結合します.
タイトルのように、みんなはStruts 2.0でjsonを使っていますが、一般的にはjsonpluginを選んでいます.私はjson-libというjarカバンを選びました.jsonpluginのbeanに対する支持がいいかどうかは分かりませんが、やはりactionを序列化するしかないです.じゃ、今私の考えを話してください.
まずJson-libで私のbeanを序列化します.もちろんこの過程は私のserviceの中に置いたのです.DWRを設定して、serviceのインターフェースを公開します.EXTがDWRを呼び出していますが、EXTオフィシャルプログラムではDWRのデータソースがサポートされていません.ネット上で強い人が書いているEXTデータソースのDWRJSを見つけて、少し修正したら私のDWRJSONJSになります.小さな変更です.布のコードを貼ります.
これは私が改めたJSです.
jsコード

   1. Ext.data.DWRProxy = function(dwrCall, pagingAndSort)   
   2. {   
   3.     Ext.data.DWRProxy.superclass.constructor.call(this);   
   4.     this.dwrCall = dwrCall;   
   5.     //this.args = args;   
   6.     this.pagingAndSort = (pagingAndSort!=undefined ? pagingAndSort : true);   
   7. };   
   8.   
   9. Ext.extend   
  10. (   
  11.     Ext.data.DWRProxy,    
  12.     Ext.data.DataProxy,    
  13.     {   
  14.     load : function(params, reader, callback, scope, arg)    
  15.     {   
  16.         if(this.fireEvent("beforeload", this, params) !== false)    
  17.         {   
  18.             var sort;   
  19.   
  20.             if(params.sort && params.dir)    
  21.                 sort = params.sort + ' ' + params.dir;   
  22.             else    
  23.                 sort = '';   
  24.   
  25.             var delegate = this.loadResponse.createDelegate(this, [reader, callback, scope, arg], 1);   
  26.             var callParams = new Array();   
  27.   
  28.             if(arg.arg)    
  29.             {   
  30.                 callParams = arg.arg.slice();   
  31.             }   
  32.   
  33.             if(this.pagingAndSort)    
  34.             {   
  35.                 callParams.push(params.start);   
  36.                 callParams.push(params.limit);   
  37.                 callParams.push(sort);   
  38.             }   
  39.   
  40.             callParams.push(delegate);   
  41.             this.dwrCall.apply(this, callParams);   
  42.         }    
  43.         else    
  44.         {   
  45.             callback.call(scope || this, null, arg, false);   
  46.         }   
  47.     },   
  48.   
  49.     loadResponse : function(listRange, reader, callback, scope, arg)    
  50.     {   
  51.         var result;   
  52.         try    
  53.         {   
  54.             result = reader.readRecords(listRange.evalJSON());   
  55.         }    
  56.         catch(e)    
  57.         {   
  58.             this.fireEvent("loadexception", this, null, response, e);   
  59.             callback.call(scope, null, arg, false);   
  60.             return;   
  61.         }   
  62.         callback.call(scope, result, arg, true);   
  63.     },   
  64.   
  65.     update : function(dataSet){},   
  66.   
  67.     updateResponse : function(dataSet)   
  68.     {}   
  69.     }   
  70. );   
  71.   
  72. Ext.data.ListRangeReader = function(meta, recordType)   
  73. {   
  74.     Ext.data.ListRangeReader.superclass.constructor.call(this, meta, recordType);   
  75.     this.recordType = recordType;   
  76. };   
  77. Ext.extend   
  78. (   
  79.     Ext.data.ListRangeReader,    
  80.     Ext.data.DataReader,    
  81.     {   
  82.         getJsonAccessor: function()   
  83.         {   
  84.             var re = /[[.]/;   
  85.             return function(expr)    
  86.             {   
  87.                 try    
  88.                 {   
  89.                     return(re.test(expr))? new Function("obj", "return obj." + expr): function(obj){return obj[expr];};   
  90.                 }   
  91.                 catch(e)   
  92.                 {}   
  93.                 return Ext.emptyFn;   
  94.             };   
  95.         }(),   
  96.   
  97.         read : function(o)   
  98.         {   
  99.             var recordType = this.recordType, fields = recordType.prototype.fields;   
 100.             //Generate extraction functions for the totalProperty, the root, the id, and for each field   
 101.             if (!this.ef)    
 102.             {   
 103.                 if(this.meta.totalProperty)    
 104.                 {   
 105.                     this.getTotal = this.getJsonAccessor(this.meta.totalProperty);   
 106.                 }   
 107.   
 108.                 if(this.meta.successProperty)    
 109.                 {   
 110.                     this.getSuccess = this.getJsonAccessor(this.meta.successProperty);   
 111.                 }   
 112.   
 113.                 if (this.meta.id)    
 114.                 {   
 115.                     var g = this.getJsonAccessor(this.meta.id);   
 116.                     this.getId = function(rec)    
 117.                     {   
 118.                         var r = g(rec);   
 119.                         return (r === undefined || r === "") ? null : r;   
 120.                     };   
 121.                 }    
 122.                 else    
 123.                 {   
 124.                     this.getId = function(){return null;};   
 125.                 }   
 126.                 this.ef = [];   
 127.                 for(var i = 0; i < fields.length; i++)   
 128.                 {   
 129.                     f = fields.items[i];   
 130.                     var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;   
 131.                     this.ef[i] = this.getJsonAccessor(map);   
 132.                 }   
 133.             }   
 134.             var records = [];   
 135.             var root = o.data, c = root.length, totalRecords = c, success = true;   
 136.   
 137.             if(this.meta.totalProperty)   
 138.             {   
 139.                 var v = parseInt(this.getTotal(o), 10);   
 140.                 if(!isNaN(v))   
 141.                 {   
 142.                     totalRecords = v;   
 143.                 }   
 144.             }   
 145.   
 146.             if(this.meta.successProperty)   
 147.             {   
 148.                 var v = this.getSuccess(o);   
 149.                 if(v === false || v === 'false')   
 150.                 {   
 151.                     success = false;   
 152.                 }   
 153.             }   
 154.   
 155.             for(var i = 0; i < c; i++)   
 156.             {   
 157.                 var n = root[i];   
 158.                 var values = {};   
 159.                 var id = this.getId(n);   
 160.                 for(var j = 0; j < fields.length; j++)   
 161.                 {   
 162.                     f = fields.items[j];   
 163.                     var v = this.ef[j](n);   
 164.                     values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);   
 165.                 }   
 166.                 var record = new recordType(values, id);   
 167.                 records[i] = record;   
 168.             }   
 169.   
 170.             return{   
 171.                 success : success,   
 172.                 records : records,   
 173.                 totalRecords : totalRecords   
 174.             };   
 175.         }   
 176.     }   
 177. );
注:上のプログラムのreaderは機能しませんでした.私はEXTのJSONREADERを使っています.
以下はEXTGridのコードです.
jsコード

   1. <#macro ext name dwrclass dwrfunction>   
   2.     "text/javascript" src="<@s.url value='/pubjs/ext-dwr.js'/>">   
   3.     "<@s.url value='/dwr/interface/${dwrclass}.js'/>">   
   4.     "<@s.url value='/dwr/engine.js'/>">   
   5.     "<@s.url value='/dwr/util.js'/>">      
   6.     "text/javascript">   
   7.   
   8.  var ds;   
   9.     var GridUI = function()   
  10.     {          
  11.         var grid; //component   
  12.         var columnModel; // definition of the columns   
  13.         if('${name}'=='userList')   
  14.         {   
  15.             function initDataSource()    
  16.             {   
  17.                   ds = new Ext.data.Store({   
  18.                     proxy: new Ext.data.DWRProxy(${dwrclass}.${dwrfunction}, true),   
  19.                        
  20.                     reader: new Ext.data.JsonReader(   
  21.                     <@s.property value="listDetail"/>),   
  22.                     remoteSort: false  
  23.                   });   
  24.        
  25.                     ds.on("load", function () {   
  26.                     });        
  27.             }   
  28.   
  29.             function getColumnModel()    
  30.             {   
  31.                 if(!columnModel) {   
  32.                     columnModel = new Ext.grid.ColumnModel(   
  33.                         <@s.property value="listClounmModel"/>   
  34.                     );   
  35.                     columnModel.defaultSortable = true;   
  36.             }   
  37.                 return columnModel;   
  38.             }      
  39.     }   
  40.     else if('${name}'=='roleList')   
  41.     {   
  42.         function initDataSource()    
  43.             {   
  44.                   ds = new Ext.data.Store({   
  45.                     proxy: new Ext.data.DWRProxy(${dwrclass}.${dwrfunction}, true),   
  46.                        
  47.                     reader: new Ext.data.JsonReader(   
  48.                     <@s.property value="roleDetail"/>),   
  49.                     remoteSort: false  
  50.                   });   
  51.        
  52.                     ds.on("load", function () {   
  53.                     });        
  54.             }   
  55.   
  56.             function getColumnModel()    
  57.             {   
  58.                 if(!columnModel) {   
  59.                     columnModel = new Ext.grid.ColumnModel(   
  60.                         <@s.property value="roleClounmModel"/>   
  61.                     );   
  62.                     columnModel.defaultSortable = true;   
  63.             }   
  64.                 return columnModel;   
  65.             }      
  66.     }      
  67.     else if('${name}'=='permList')   
  68.     {   
  69.         function initDataSource()    
  70.             {   
  71.                   ds = new Ext.data.Store({   
  72.                     proxy: new Ext.data.DWRProxy(${dwrclass}.${dwrfunction}, true),   
  73.                        
  74.                     reader: new Ext.data.JsonReader(   
  75.                     <@s.property value="PermissionDetail"/>),   
  76.                     remoteSort: false  
  77.                   });   
  78.        
  79.                     ds.on("load", function () {   
  80.                     });        
  81.             }   
  82.   
  83.             function getColumnModel()    
  84.             {   
  85.                 if(!columnModel) {   
  86.                     columnModel = new Ext.grid.ColumnModel(   
  87.                         <@s.property value="PermissionClounmModel"/>   
  88.                     );   
  89.                     columnModel.defaultSortable = true;   
  90.             }   
  91.                 return columnModel;   
  92.             }      
  93.     }              
  94.         function buildGrid()    
  95.         {                  
  96.             grid = new Ext.grid.Grid(   
  97.                 '${name}',   
  98.                 {   
  99.                     ds: ds,   
 100.                     cm: getColumnModel(),   
 101.                     autoSizeColumns: true,   
 102.                     selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),   
 103.                     loadMask: true  
 104.                 }   
 105.             );   
 106.                
 107.                
 108.             grid.render();   
 109.             grid.getSelectionModel().selectFirstRow();   
 110.             //         
 111.             grid.addListener('rowcontextmenu', contextmenu);   
 112.             var gridFoot = grid.getView().getFooterPanel(true);   
 113.             var paging = new Ext.PagingToolbar   
 114.             (   
 115.                 gridFoot,   
 116.                 ds,   
 117.                 {   
 118.                     pageSize:<@s.property value="perPageCount"/>,   
 119.                     displayInfo:true,   
 120.                     beforePageText:'<@s.text name="System.list.page"/>',   
 121.                     afterPageText:'<@s.text name="System.list.pagedetails"/>',   
 122.                     displayMsg: '<@s.text name="System.list.gridList"/>'   
 123.                 }   
 124.             );   
 125.             /*paging.add  
 126.             (  
 127.                 '_',  
 128.                 {  
 129.                     pressed: true,  
 130.                     enableToggle:true,  
 131.                     text: '<@s.text name="System.list.details"/>',  
 132.                     cls: 'x-btn-text-icon details',  
 133.                     toggleHandler: toggleDetails  
 134.                 }  
 135.             );*/  
 136.         }   
 137.        
 138.         function toggleDetails(btn, pressed)   
 139.         {   
 140.             if(pressed)   
 141.             {   
 142.                 alert('Oh!Who hit me?');   
 143.             }   
 144.         }   
 145.        
 146.         return{   
 147.             init : function() {   
 148.                 initDataSource();   
 149.                 ds.load({params:{start:0, limit:<@s.property value="perPageCount"/>}, callback:callme});               
 150.                 buildGrid();   
 151.             },   
 152.                
 153.             getStore: function() {   
 154.                 return ds;   
 155.             }   
 156.         }   
 157.     }();   
 158.     function callme(tt)   
 159.     {   
 160.     }   
 161.     Ext.onReady(GridUI.init, GridUI, true);    
 162.        
 163.    
以下は業務のコードです.
javaコード

   1. public JSONObject getPageData(String queryString, int cpage, int pageSize,Serializable[] params) throws DFLogError   
   2.     {   
   3.         List results;   
   4.         JPage pageData = null;   
   5.         int total;   
   6.         Session s = this.getSession();   
   7.         try  
   8.         {   
   9.             Query query = this.getQuery(queryString, params, s);   
  10.             total = query.list().size();   
  11.             results = query.setFirstResult(cpage).setMaxResults(pageSize).list();   
  12.             pageData = new JPage(total, cpage);   
  13.             pageData.setData(results);   
  14.             return JSONObject.fromBean(pageData,StringUtils.commaDelimitedListToStringArray("roles,authorities"));   
  15.         }   
  16.         catch (HibernateException e)   
  17.         {   
  18.             log.error("Error in BaseDao.getPageData(String hql, int cpage, int pageSize)",e);   
  19.             throw new DFLogError("Error in BaseDao.getPageData(String hql, int cpage, int pageSize)",e);   
  20.         }   
  21.         finally  
  22.         {   
  23.             this.closeSession(s); 
              }