Flex4之DataGrid四个的示例【客户端和服务器端】

首先说明下:以下的四个例子中每一个都含有客户端获取DataGrid数据的代码

下面的每个mxml中都涉及用到的组件mxml,位于com/control目录下

Xml代码 复制代码
  1. <SPAN style="FONT-SIZE: medium"><?xml version="1.0" encoding="utf-8"?>  
  2. <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="white">  
  3.     <mx:Script>  
  4.         <![CDATA[  
  5.                   import mx.collections.ArrayCollection;  
  6.                   import mx.events.ItemClickEvent;  
  7.                   import flash.events.KeyboardEvent;  
  8.                   import mx.controls.DataGrid;  
  9.                   import mx.validators.NumberValidator;  
  10.  
  11.                   [Bindable]  
  12.                   [Embed(source='assets/first.jpg')]  
  13.                   private var firstIcon:Class;                  
  14.                   private var firstPage:uint;   
  15.                     
  16.                   [Bindable]  
  17.                   [Embed(source='assets/pre.jpg')]  
  18.                   private var preIcon:Class;  
  19.                   private var prePage:uint;   
  20.               
  21.                   [Bindable]  
  22.                   [Embed(source='assets/next.jpg')]  
  23.                   private var nextIcon:Class;  
  24.                   private var nextPage:uint;   
  25.  
  26.                   [Bindable]  
  27.                   [Embed(source='assets/last.jpg')]  
  28.                   private var lastIcon:Class;  
  29.                   private var lastPage:uint;  
  30.                              
  31.                   //页码条数据,绑定  
  32.                   [Bindable]  
  33.                   private var nav:ArrayCollection = new ArrayCollection();  
  34.                     
  35.                   //默认起始页码,第1页  
  36.                   private var currentPageIndex:uint = 0;  
  37.                     
  38.                   //是否已初始化  
  39.                   private var isInit:Boolean=true;                    
  40.                     
  41.                   //总页数  
  42.                   private var totalPages:uint = 0;  
  43.                     
  44.                   //是否重绘页码条,当使用服务端分页时使用  
  45.                   private var isCreateNavBar:Boolean = true;  
  46.                                     
  47.                   /************************************************************/  
  48.                     
  49.                   //显示到Grid的数据  
  50.                   [Bindable]  
  51.                   public var viewData:ArrayCollection=null;  
  52.                     
  53.                   //所有的数据  
  54.                   public var orgData:ArrayCollection=null;  
  55.                     
  56.                   //每页记录数下拉框  
  57.                   public var pageSizeDropDownListData:ArrayCollection=null;  
  58.                     
  59.                   // 每页记录数   
  60.                   public var pageSize:uint = 5;   
  61.                                    
  62.                   // 页码条上显示页码的个数  
  63.                   public var navSize:uint = 5;  
  64.                     
  65.                   //记录总数,调用服务端发页时使用  
  66.                   public var totalRecord:int=0;  
  67.                     
  68.                   //分页函数  
  69.                   public var pagingFunction:Function=null;  
  70.                     
  71.                   //分页条对应的Grid  
  72.                   public var dataGrid:DataGrid=null;  
  73.                     
  74.                   /***************************************************************/  
  75.                     
  76.                   public function dataBind(isServerSide:Boolean=false):void{  
  77.                         //是否初始化  
  78.                         if(isInit){  
  79.                             if(pageSizeDropDownListData==null){  
  80.                                 pageSizeDropDownListData = new ArrayCollection();  
  81.                                 pageSizeDropDownListData.addItem({label:5,data:5});  
  82.                                 pageSizeDropDownListData.addItem({label:10,data:10});  
  83.                                 pageSizeDropDownListData.addItem({label:20,data:20});  
  84.                                 pageSizeDropDownListData.addItem({label:30,data:30});                             
  85.                             }  
  86.                             pageSizeComobox.dataProvider=pageSizeDropDownListData;  
  87.                             isInit=false;  
  88.                         }  
  89.                         //                                                                
  90.                         refreshDataProvider(currentPageIndex,isCreateNavBar,pageSize,isServerSide);  
  91.                   }  
  92.                     
  93.                     
  94.                     
  95.                   /**  
  96.                     * 构建页码条  
  97.                     * pages:总页数  
  98.                     * pageIndex:当前页(注意,从0开始)  
  99.                     *  
  100.                    */  
  101.                   private function createNavBar(pageIndex:uint = 0):void{  
  102.                       nav.removeAll();  
  103.                       //向前图标操作,first,Pre  
  104.                       if( pageIndex > 1 ){  
  105.                             firstPage=0;  
  106.                             firstNavBtn.visible=true;  
  107.                             //  
  108.                             var intLFive:int = pageIndex-navSize; // calculate start of last 5;  
  109.                             //  
  110.                             prePage=intLFive;  
  111.                             preNavBtn.visible=true;  
  112.                       }  
  113.                       else{  
  114.                             firstNavBtn.visible=false;  
  115.                             preNavBtn.visible=false;  
  116.                       }  
  117.                       //页码条          
  118.                       for( var x:uint = 0; x < navSize; x++){  
  119.                             var pg:uint = x + pageIndex;  
  120.                             nav.addItem({label: pg + 1,data: pg});  
  121.                             //    
  122.                             var pgg:uint = pg+1;  
  123.                             if(pgg>=totalPages){ //搜索到最后一个页码,停止添加到navbar  
  124.                                 x=navSize;   
  125.                             }  
  126.                       }  
  127.                       //计算最后一组页码条中第一个页码的页码编号  
  128.                       var lastpage:Number = 0;  
  129.                       for( var y:uint = navSize; y <= totalPages-1;y = y + navSize ){ //lets calculate the lastpage button  
  130.                             if(y+5 > navSize){  
  131.                                 lastpage = y;  
  132.                             }  
  133.                       }                     
  134.                       //向后图标  
  135.                       if( pg < totalPages - 1 ){  
  136.                             nextPage=pg + 1;  
  137.                             nextNavBtn.visible=true;  
  138.                             lastPage=lastpage;  
  139.                             lastNavBtn.visible=true;  
  140.                       }  
  141.                       else{                                
  142.                             nextNavBtn.visible=false;  
  143.                             lastNavBtn.visible=false;  
  144.                       }  
  145.                   }  
  146.                     
  147.                   /**  
  148.                   * 页码按钮按下(页码条点击)  
  149.                   */   
  150.                   private function navigatePage(event:ItemClickEvent):void  
  151.                   {  
  152.                         refreshDataProvider(event.item.data,false);     
  153.                   }  
  154.                     
  155.                   /**  
  156.                   * 页码按钮按下,first,pre,next,last  
  157.                   */   
  158.                   private function navigateButtonClick(pageString:String):void{  
  159.                         var pageIndex:uint=0;  
  160.                         switch(pageString){  
  161.                             case "firstPage":  
  162.                                 pageIndex=firstPage;  
  163.                                 break;  
  164.                             case "prePage":  
  165.                                 pageIndex=prePage;  
  166.                                 break;  
  167.                             case "nextPage":  
  168.                                 pageIndex=nextPage;  
  169.                                 break;  
  170.                             default:    //lastPage  
  171.                                 pageIndex=lastPage;  
  172.                         }  
  173.                         //  
  174.                         refreshDataProvider(pageIndex);  
  175.                   }  
  176.                     
  177.                   /**  
  178.                   * 更新数据源,更新表格显示数据  
  179.                   */   
  180.                   private function refreshDataProvider(pageIndex:uint,isCreateNavBar:Boolean=true,pageSize:uint=0,resultReturn:Boolean=false):void{  
  181.                       //分页函数  
  182.                       if(dataGrid==null) return;  
  183.                       currentPageIndex=pageIndex;  
  184.                       if(pageSize==0){  
  185.                             pageSize=this.pageSize;   
  186.                       }else{  
  187.                             this.pageSize=pageSize;  
  188.                             if(!resultReturn) totalPages = Math.ceil(orgData.length/pageSize);  
  189.                       }                     
  190.                       if(!resultReturn){                                                                                  
  191.                               if(this.pagingFunction!=null){  
  192.                                     pagingFunction(pageIndex,pageSize);  
  193.                                     this.isCreateNavBar=isCreateNavBar;   
  194.                               }  
  195.                               else{  
  196.                                     viewData = new ArrayCollection( orgData.source.slice((pageIndex * pageSize),(pageIndex * pageSize) + pageSize) );                     
  197.                                     dataGrid.dataProvider=viewData;  
  198.                                     pageNumber.text=(pageIndex+1).toString();  
  199.                                       
  200.                                     totalRecordLabel.text = '总记录数:' + orgData.length.toString();                                                            
  201.                               }  
  202.                       }  
  203.                       else{  
  204.                             dataGrid.dataProvider=orgData;  
  205.                             totalPages = Math.ceil(totalRecord/pageSize);  
  206.                             pageNumber.text=(pageIndex+1).toString();  
  207.                             totalRecordLabel.text = '总记录数:' + totalRecord.toString()              
  208.                       }  
  209.                       totalPagesLabel.text = '总页数:' + totalPages;  
  210.                       if(isCreateNavBar) createNavBar(pageIndex);  
  211.                   }  
  212.                   //  
  213.                   /**  
  214.                   * 每页记录数变更(下拉框选择)  
  215.                   */   
  216.                   private function pageSizeSelectChange():void{  
  217.                         refreshDataProvider(0,true,uint(pageSizeComobox.value));  
  218.                   }                  
  219.                   /**  
  220.                   * 页码变更(直接输入)  
  221.                   */   
  222.                   private function pageIndexInsertChange(event:Event):void{  
  223.                         var keyboardEvent:KeyboardEvent=event as KeyboardEvent;  
  224.                         if(keyboardEvent!=null&&keyboardEvent.keyCode== Keyboard.ENTER){  
  225.                             var pageIndex:uint=uint(pageNumber.text)-1;  
  226.                             if(pageIndex>0&&pageIndex<totalPages&&pageIndex!=currentPageIndex){  
  227.                                 refreshDataProvider(pageIndex);  
  228.                             }  
  229.                             else{                                 
  230.                                 pageNumber.text = (currentPageIndex+1).toString();  
  231.                             }  
  232.                         }  
  233.                   }       
  234.                   /**  
  235.                   * 查看所有  
  236.                   */   
  237.                   private function viewAll():void{  
  238.                         var tempTotalRecord:uint=0;                 
  239.                         if(pagingFunction!=null) tempTotalRecord=totalRecord;  
  240.                         else tempTotalRecord=orgData.length;  
  241.                         //  
  242.                         pageSizeComobox.text=tempTotalRecord.toString();  
  243.                         pageSizeComobox.selectedIndex=-1;  
  244.                         refreshDataProvider(0,true,tempTotalRecord);  
  245.                   }  
  246.         ]]>  
  247.     </mx:Script>  
  248.     <mx:HBox paddingTop="8">  
  249.         <mx:Button id="firstNavBtn" icon="{firstIcon}" width="10" height="10" click="navigateButtonClick('firstPage');" />  
  250.         <mx:Button id="preNavBtn" icon="{preIcon}" width="7" height="10" click="navigateButtonClick('prePage');"/>  
  251.     </mx:HBox>  
  252.     <mx:LinkBar id="pageNav" itemClick="navigatePage(event)" dataProvider="{nav}"/>  
  253.     <mx:HBox paddingTop="8">  
  254.         <mx:Button id="nextNavBtn" icon="{nextIcon}" width="7" height="10" click="navigateButtonClick('nextPage');"/>  
  255.         <mx:Button id="lastNavBtn" icon="{lastIcon}" width="10" height="10" click="navigateButtonClick('lastPage');"/>  
  256.     </mx:HBox>  
  257.     <mx:VRule height="25"/>  
  258.     <mx:Label paddingTop="3" id="totalPagesLabel" text=""/>  
  259.     <mx:Label paddingTop="3" id="totalRecordLabel" text=""/>  
  260.     <mx:Label paddingTop="3" text="每页记录:"/>  
  261.     <mx:ComboBox id="pageSizeComobox" cornerRadius="0" paddingLeft="0" fontWeight="normal" width="50" arrowButtonWidth="10" change="pageSizeSelectChange()"/>  
  262.     <mx:Label paddingTop="3" text="页码:"/>  
  263.     <mx:TextInput id="pageNumber" width="40" keyDown="pageIndexInsertChange(event);"/>  
  264.     <mx:LinkButton id="viewAllLinkBtn" label="查看所有" click="viewAll();"/>                 
  265. </mx:HBox>      
  266.   
  267. </SPAN>  

 

 

 

第一:  HTTPService获取服务器端数据显示DataGrid

         HTTPService的方式一

         mxml内容

     

Xml代码 复制代码
  1. <SPAN style="FONT-SIZE: medium"><?xml version="1.0" encoding="utf-8"?>  
  2. <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"    
  3.                xmlns:s="library://ns.adobe.com/flex/spark"    
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"  
  5.                xmlns:control="com.control.*"    
  6.                creationComplete="creationCompleteHandle();myservice.send()"  
  7.                minWidth="955" minHeight="600">  
  8.     <fx:Style>  
  9.         Application{   
  10.             fontSize:12;   
  11.         }   
  12.     </fx:Style>  
  13.     <fx:Declarations>  
  14.         <!-- 将非可视元素(例如服务、值对象)放在此处 这个HTTPService使用时一定要提前调用send方法-->  
  15.         <s:HTTPService id="myservice" url="http://localhost:8080/ClientServerDataGrid/find.do" result="myservice_resultHandler(event)" />  
  16.     </fx:Declarations>  
  17.        
  18.     <fx:Script>  
  19.         <![CDATA[  
  20.             import com.adobe.serialization.json.JSON;  
  21.               
  22.             import mx.collections.ArrayCollection;  
  23.             import mx.controls.Alert;  
  24.             import mx.rpc.events.FaultEvent;  
  25.             import mx.rpc.events.ResultEvent;  
  26.               
  27.             private var pageIndex:int=0;  
  28.               
  29.             private var pageSize:int=5;  
  30.               
  31.             private function creationCompleteHandle():void{  
  32.                 var orgData:ArrayCollection = new ArrayCollection();  
  33.                 for( var x:uint = 1; x <= 555; x++ )  
  34.                 {  
  35.                     var obj:Object = new Object();  
  36.                     obj.ID = "id " + x.toString();  
  37.                     obj.Code="order "+x;  
  38.                     obj.Total=x*1000;  
  39.                     obj.Customer= "customer "+x;  
  40.                     obj.Register = "employee";  
  41.                     obj.Memo="memo "+x;                   
  42.                     obj.State="auditing state";                   
  43.                     orgData.addItem(obj);  
  44.                 }  
  45.                 clientPagingBar1.dataGrid=DataGrid1;  
  46.                 clientPagingBar1.orgData=orgData;  
  47.                 clientPagingBar1.dataBind();  
  48.                   
  49.                   
  50.             }  
  51.               
  52.           
  53.               
  54.               
  55.              protected function myservice_resultHandler(event:ResultEvent):void  
  56.             {  
  57.             var rawData:String = String(event.result);    
  58.             //decode the data to ActionScript using the JSON API    
  59.             //in this case, the JSON data is a serialize Array of Objects.  
  60.               
  61.             var arr:Array = (JSON.decode(rawData) as Array);    
  62.             var dataArray:ArrayCollection = new ArrayCollection(arr);   
  63.             //Alert.show(dataArray.getItemAt(0).id);  
  64.             clientPagingBar2.dataGrid=DataGrid2;  
  65.             clientPagingBar2.orgData=dataArray;  
  66.             clientPagingBar2.dataBind();  
  67.             }   
  68.               
  69.         ]]>  
  70.     </fx:Script>  
  71.        
  72.     <mx:VBox>        
  73.         <mx:Label text="客户端分页" />  
  74.         <mx:Canvas backgroundColor="white">  
  75.             <mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">  
  76.                 <mx:DataGrid id="DataGrid1" verticalScrollPolicy="on" horizontalScrollPolicy="off">  
  77.                     <mx:columns>  
  78.                         <mx:DataGridColumn headerText="订单ID" dataField="ID" />  
  79.                         <mx:DataGridColumn headerText="订单编码" dataField="Code" />  
  80.                         <mx:DataGridColumn headerText="金额" dataField="Total" />  
  81.                         <mx:DataGridColumn headerText="客户" dataField="Customer" />  
  82.                         <mx:DataGridColumn headerText="销售员" dataField="Register" />  
  83.                         <mx:DataGridColumn headerText="备注说明" dataField="Memo" />  
  84.                         <mx:DataGridColumn headerText="状态" dataField="State" />                  
  85.                     </mx:columns>  
  86.                 </mx:DataGrid>  
  87.                 <control:PagingBar id="clientPagingBar1" />  
  88.             </mx:VBox>  
  89.         </mx:Canvas>  
  90.            
  91.         <mx:Label text="服务器端分页" />  
  92.         <mx:Canvas backgroundColor="white">  
  93.             <mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">  
  94.                 <mx:DataGrid id="DataGrid2" verticalScrollPolicy="on" horizontalScrollPolicy="off">  
  95.                     <mx:columns>  
  96.                         <mx:DataGridColumn headerText="订单ID" dataField="id" />  
  97.                         <mx:DataGridColumn headerText="订单编码" dataField="code" />  
  98.                         <mx:DataGridColumn headerText="金额" dataField="total" />  
  99.                         <mx:DataGridColumn headerText="客户" dataField="customer" />  
  100.                         <mx:DataGridColumn headerText="销售员" dataField="register" />  
  101.                         <mx:DataGridColumn headerText="备注说明" dataField="memo" />  
  102.                         <mx:DataGridColumn headerText="状态" dataField="state" />                  
  103.                     </mx:columns>  
  104.                 </mx:DataGrid>  
  105.                 <control:PagingBar id="clientPagingBar2" />  
  106.             </mx:VBox>  
  107.         </mx:Canvas>  
  108.     </mx:VBox>  
  109.        
  110. </s:Application>  
  111. </SPAN>  

 

     HTTPService的方式二

  

Xml代码 复制代码
  1. <SPAN style="FONT-SIZE: medium"><?xml version="1.0" encoding="utf-8"?>  
  2. <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"    
  3.                xmlns:s="library://ns.adobe.com/flex/spark"    
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"  
  5.                xmlns:control="com.control.*"    
  6.                creationComplete="creationCompleteHandle()"  
  7.                minWidth="955" minHeight="600">  
  8.     <fx:Style>  
  9.         Application{   
  10.             fontSize:12;   
  11.         }   
  12.     </fx:Style>  
  13.     <fx:Declarations>  
  14.         <!-- 将非可视元素(例如服务、值对象)放在此处 这个HTTPService使用时一定要提前调用send方法-->  
  15.         <s:HTTPService id="myservice"  />  
  16.     </fx:Declarations>  
  17.        
  18.     <fx:Script>  
  19.         <![CDATA[  
  20.             import com.adobe.serialization.json.JSON;  
  21.               
  22.             import mx.collections.ArrayCollection;  
  23.             import mx.controls.Alert;  
  24.             import mx.rpc.events.FaultEvent;  
  25.             import mx.rpc.events.ResultEvent;  
  26.             import mx.utils.URLUtil;  
  27.               
  28.             private var pageIndex:int=0;  
  29.               
  30.             private var pageSize:int=5;  
  31.               
  32.             private function creationCompleteHandle():void{  
  33.                 var orgData:ArrayCollection = new ArrayCollection();  
  34.                 for( var x:uint = 1; x <= 555; x++ )  
  35.                 {  
  36.                     var obj:Object = new Object();  
  37.                     obj.ID = "id " + x.toString();  
  38.                     obj.Code="order "+x;  
  39.                     obj.Total=x*1000;  
  40.                     obj.Customer= "customer "+x;  
  41.                     obj.Register = "employee";  
  42.                     obj.Memo="memo "+x;                   
  43.                     obj.State="auditing state";                   
  44.                     orgData.addItem(obj);  
  45.                 }  
  46.                 clientPagingBar1.dataGrid=DataGrid1;  
  47.                 clientPagingBar1.orgData=orgData;  
  48.                 clientPagingBar1.dataBind();  
  49.                   
  50.                 myservice.url="http://localhost:8080/ClientServerDataGrid/find.do";  
  51.                 myservice.showBusyCursor=true;  
  52.                 myservice.send();  
  53.                 myservice.addEventListener(ResultEvent.RESULT,hsResultHandler);   
  54.                 myservice.addEventListener(FaultEvent.FAULT,hsFaultHandler);   
  55.             }  
  56.             private function hsResultHandler(event:ResultEvent):void{     
  57.                 var rawData:String = String(event.result);    
  58.                 //decode the data to ActionScript using the JSON API    
  59.                 //in this case, the JSON data is a serialize Array of Objects.  
  60.                   
  61.                 var arr:Array = (JSON.decode(rawData) as Array);    
  62.                 var dataArray:ArrayCollection = new ArrayCollection(arr);   
  63.                 //Alert.show(dataArray.getItemAt(0).id);  
  64.                 clientPagingBar2.dataGrid=DataGrid2;  
  65.                 clientPagingBar2.orgData=dataArray;  
  66.                 clientPagingBar2.dataBind();  
  67.             }     
  68.             private function hsFaultHandler(e:FaultEvent):void{     
  69.                 Alert.show(e.fault.toString(),'http请求错误');     
  70.             }     
  71.               
  72.               
  73.               
  74.         ]]>  
  75.     </fx:Script>  
  76.        
  77.     <mx:VBox>        
  78.         <mx:Label text="客户端分页" />  
  79.         <mx:Canvas backgroundColor="white">  
  80.             <mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">  
  81.                 <mx:DataGrid id="DataGrid1" verticalScrollPolicy="on" horizontalScrollPolicy="off">  
  82.                     <mx:columns>  
  83.                         <mx:DataGridColumn headerText="订单ID" dataField="ID" />  
  84.                         <mx:DataGridColumn headerText="订单编码" dataField="Code" />  
  85.                         <mx:DataGridColumn headerText="金额" dataField="Total" />  
  86.                         <mx:DataGridColumn headerText="客户" dataField="Customer" />  
  87.                         <mx:DataGridColumn headerText="销售员" dataField="Register" />  
  88.                         <mx:DataGridColumn headerText="备注说明" dataField="Memo" />  
  89.                         <mx:DataGridColumn headerText="状态" dataField="State" />                  
  90.                     </mx:columns>  
  91.                 </mx:DataGrid>  
  92.                 <control:PagingBar id="clientPagingBar1" />  
  93.             </mx:VBox>  
  94.         </mx:Canvas>  
  95.            
  96.         <mx:Label text="服务器端分页" />  
  97.         <mx:Canvas backgroundColor="white">  
  98.             <mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">  
  99.                 <mx:DataGrid id="DataGrid2" verticalScrollPolicy="on" horizontalScrollPolicy="off">  
  100.                     <mx:columns>  
  101.                         <mx:DataGridColumn headerText="订单ID" dataField="id" />  
  102.                         <mx:DataGridColumn headerText="订单编码" dataField="code" />  
  103.                         <mx:DataGridColumn headerText="金额" dataField="total" />  
  104.                         <mx:DataGridColumn headerText="客户" dataField="customer" />  
  105.                         <mx:DataGridColumn headerText="销售员" dataField="register" />  
  106.                         <mx:DataGridColumn headerText="备注说明" dataField="memo" />  
  107.                         <mx:DataGridColumn headerText="状态" dataField="state" />                  
  108.                     </mx:columns>  
  109.                 </mx:DataGrid>  
  110.                 <control:PagingBar id="clientPagingBar2" />  
  111.             </mx:VBox>  
  112.         </mx:Canvas>  
  113.     </mx:VBox>  
  114.        
  115. </s:Application>  
  116. </SPAN>  

第二:URLRequest方式获取

  mxml内容

   

 

针对上面两种方式的servlet处理类为

  

package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

public class FindDataServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
             this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("执行Servlet了哦。。。。。。。。。。。。");
		List<MyObject> orgData=new ArrayList<MyObject>();
		for(int x= 1; x <= 555; x++ )
		{
			MyObject ob=new MyObject();
			ob.setId("CHENEY"+x);
	        ob.setCode("HENAN"+x);
			ob.setTotal(x*10);
			ob.setCustomer("CUS"+x);
			ob.setRegister("EMP"+x);
            ob.setMemo("MEMO"+x);
			ob.setState("STATE"+x);
			orgData.add(ob);
		}
	   JSONArray json=JSONArray.fromObject(orgData);
	   String datas=json.toString();
	   System.out.println(datas);
	   response.getWriter().write(datas);
	}

}

 当然这里JAVA程序也用到JSON相关类,一般要使用JSON的话要使用到六个包

 

 第三:RemoteObject 获取方式

    mxml内容

   

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx"
			   xmlns:control="com.control.*" 
			   creationComplete="creationCompleteHandle()"
			   minWidth="955" minHeight="600">
	<fx:Style>
		Application{
			fontSize:12;
		}
	</fx:Style>
	<fx:Declarations>
		<s:RemoteObject id="findData" destination="findData" result="findDate_resultHandler(event)"/>
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import com.adobe.serialization.json.JSON;
			
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			
			private var pageIndex:int=0;
			
			private var pageSize:int=5;
			
			private function creationCompleteHandle():void{
				var orgData:ArrayCollection = new ArrayCollection();
				for( var x:uint = 1; x <= 555; x++ )
				{
					var obj:Object = new Object();
					obj.ID = "id " + x.toString();
					obj.Code="order "+x;
					obj.Total=x*1000;
					obj.Customer= "customer "+x;
					obj.Register = "employee";
					obj.Memo="memo "+x;	            	
					obj.State="auditing state";	            	
					orgData.addItem(obj);
				}
				clientPagingBar1.dataGrid=DataGrid1;
				clientPagingBar1.orgData=orgData;
				clientPagingBar1.dataBind();
				
				
				findData.findData();
			}
			
			 protected function findDate_resultHandler(event:ResultEvent):void
			{
				 var rawData:String = String(event.result);  
				 //decode the data to ActionScript using the JSON API  
				 //in this case, the JSON data is a serialize Array of Objects.
				 
				 var arr:Array = (JSON.decode(rawData) as Array);  
				 var dataArray:ArrayCollection = new ArrayCollection(arr); 
				 //Alert.show(dataArray.getItemAt(0).id);
				 clientPagingBar2.dataGrid=DataGrid2;
				 clientPagingBar2.orgData=dataArray;
				 clientPagingBar2.dataBind();
			} 
			

		

		]]>
	</fx:Script>
	
	<mx:VBox>		
		<mx:Label text="客户端分页" />
		<mx:Canvas backgroundColor="white">
			<mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">
				<mx:DataGrid id="DataGrid1" verticalScrollPolicy="on" horizontalScrollPolicy="off">
					<mx:columns>
						<mx:DataGridColumn headerText="订单ID" dataField="ID" />
						<mx:DataGridColumn headerText="订单编码" dataField="Code" />
						<mx:DataGridColumn headerText="金额" dataField="Total" />
						<mx:DataGridColumn headerText="客户" dataField="Customer" />
						<mx:DataGridColumn headerText="销售员" dataField="Register" />
						<mx:DataGridColumn headerText="备注说明" dataField="Memo" />
						<mx:DataGridColumn headerText="状态" dataField="State" />		    	
					</mx:columns>
				</mx:DataGrid>
				<control:PagingBar id="clientPagingBar1" />
			</mx:VBox>
		</mx:Canvas>
		
		<mx:Label text="服务器端分页" />
		<mx:Canvas backgroundColor="white">
			<mx:VBox width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">
				<mx:DataGrid id="DataGrid2" verticalScrollPolicy="on" horizontalScrollPolicy="off">
					<mx:columns>
						<mx:DataGridColumn headerText="订单ID" dataField="id" />
						<mx:DataGridColumn headerText="订单编码" dataField="code" />
						<mx:DataGridColumn headerText="金额" dataField="total" />
						<mx:DataGridColumn headerText="客户" dataField="customer" />
						<mx:DataGridColumn headerText="销售员" dataField="register" />
						<mx:DataGridColumn headerText="备注说明" dataField="memo" />
						<mx:DataGridColumn headerText="状态" dataField="state" />		    	
					</mx:columns>
				</mx:DataGrid>
				<control:PagingBar id="clientPagingBar2" />
			</mx:VBox>
		</mx:Canvas>
	</mx:VBox>
	
</s:Application>

 

  web-info/flex/remote-config.xml

  

<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" 
    class="flex.messaging.services.RemotingService">

    <adapters>
        <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>

    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>
     <destination id="findData" >
     <properties>
        <source>com.test.FindGridData</source>
     </properties>
     </destination>
</service>

  处理类

 

package com.test;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

public class FindGridData {

	public String findData(){
		System.out.println("执行我了。。。。。。。。。。。。。。。");
		List<MyObject> orgData=new ArrayList<MyObject>();
		for(int x= 1; x <= 555; x++ )
		{
			MyObject ob=new MyObject();
			ob.setId("CHENEY"+x);
	        ob.setCode("HENAN"+x);
			ob.setTotal(x*10);
			ob.setCustomer("CUS"+x);
			ob.setRegister("EMP");
            ob.setMemo("MEMO"+x);
			ob.setState("STATE");
			orgData.add(ob);
		}
		 JSONArray json=JSONArray.fromObject(orgData);
		   String datas=json.toString();
		   System.out.println(datas);
	  return datas;
	}
	
}

 

   四种方式显示图效果一样

 

 

最后附上corelib.swc和java相关的json必须jar包

posted on 2012-02-25 10:45  唐朝  阅读(6174)  评论(0编辑  收藏  举报