有关Flex的DataGrid文章的确不少,都是零零碎碎的,目前还没有发现有个完整的例子供网友参考,这次我花了两天时间做了下Flex关于DataGrid一个指标数据管理系统,当然设计到的mxml会很多,大都是与DataGrid相关,我就抽取最常用的DataGrid的增删改同步数据库及页面数据来讲解
首先整理下思路,首先无论是删除还是修改,必须得获取当前行所在的记录,那么可以设置个全局变量,当DataGrid的itemClick事件出发时将选中的行赋给全局变量
[Bindable]public var acItemsSelected:Object;;
//事件方法
protected function myGrid_itemClickHandler(event:ListEvent):void
{
acItemsSelected = myGrid.selectedItem;
}
这样的话就可以获得了当前选中的对象了
如果删除和修改的话,通常传到后台的肯定含有对象的ID项,那么这个ID是怎么获取的呢,通过acItemsSelected.xxxId能获取,那么这个xxxId必须是在DataGrid中有,设置为不显示就好了,例如我就是这么做的
<mx:DataGridColumn visible="false" dataField="targetCalId" />
这样的话,要更改的数据等都能通过ID传到后台查询相应对象更改删除了,接下来的事是比较重要的,如果光删除数据库是不行的,页面数据也要保持同步,关于dataGrid也没有好的刷新方法,所以你上网一搜,可能有的人会告诉你对于删除这样做:dataArray.removeItemAt(myGrid.selectedIndex);
增加这样做:dataArray.addItemAt(obj,0);
修改这样做:dataArray.setItemAt(obj,myGrid.selectedIndex);
这里说的dataArray是指的是DataGrid的DataProvider的值集合【当然肯定得声明称全局变量】
这样的写法呢可能你觉得,哎,是对的,其实不然,这并没有真正起到作用,对于FLEX来说缓存是相当大的,不行的话你通过这个修改行记录的属性后,再点这行记录的属性编辑页面发现值根本没改,所以所没有进行二次查询数据库了,利用的是缓存。即便是你调用了初始化查询数据库的那个方法,也是不行的,还是有缓存,最好的做法就是,抛弃上面的三种写法,只需要两步就可以实现刷新,第一初始化DataGrid的那个方法请求必须是URLRequest 的,添加一个参数类似于
var u:URLVariables=new URLVariables("temp="+Math.random());
当然不一定非要是temp什么名字都行,然后在返回操作成功提示后调用这个初始化方法,你会发现真的起作用了。
其实建议关于URLRequest传参数的最好带上这个参数,也不费事,可以在很多场合下解决缓存不更新问题
说了这么多其实就是先做好个思想准备,理清思路,下面我就贴上我的一段代码
mxml文件
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="668" height="326"
creationComplete="initComponent()"
title="指标计量单位"
fontSize="15"
close="closeWindow()">
<s:layout>
<s:VerticalLayout />
</s:layout>
<fx:Declarations>
<mx:StringValidator id="sval_1" source="{targetTypeName}" property="text"
tooShortError="字符串太短了,请输入最少4个字符. "
tooLongError="字符串太长了,请输入最长20个字符. "
minLength="4" maxLength="20"
trigger="{myButton}" triggerEvent="click"
/>
<mx:StringValidator id="sval_2" source="{targetCal}" property="text"
tooShortError="字符串太短了,请输入最少4个字符. "
tooLongError="字符串太长了,请输入最长20个字符. "
minLength="4" maxLength="20"
trigger="{myButton}" triggerEvent="click"
/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import com.adobe.serialization.json.JSON;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.ListEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.ResultEvent;
import mx.utils.URLUtil;
import mx.validators.Validator;
import org.osmf.utils.URL;
[Bindable]public static var mainApp:DataCenterTargetPreserve = null;
[Bindable]public var gsMyString:String;
[Bindable]public var gnMyNumber:Number;
[Bindable]public var acItemsSelected:Object;
[Bindable]
public var dataArray:ArrayCollection;
private function initComponent():void
{
var u:URLVariables=new URLVariables("temp="+Math.random());
var r:URLRequest=new URLRequest();
r.data=u;
r.method=URLRequestMethod.POST;
r.url=mainApp.urls+"/findTargetCal.do";
var l:URLLoader=new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE, comp2);
}
function comp2(e:Event):void
{
var l:URLLoader=URLLoader(e.target);
var array:Array=JSON.decode(String(l.data)) as Array;
dataArray=new ArrayCollection(array);
myGrid.dataProvider=dataArray;
}
private function closeWindow():void
{
PopUpManager.removePopUp(this);
}//closeWindow
private function showFinalSelection(oEvent:Event):void
{
//mainApp.tiFinalSelection.text = oEvent.target.selectedItem.album;
}//showFinalSelection
protected function button1_clickHandler(event:MouseEvent):void
{
PopUpManager.removePopUp(this);
}
protected function button2_clickHandler(event:MouseEvent):void
{
var all:Array=Validator.validateAll([sval_1,sval_2]);
if(all.length==0){
var v:URLVariables=new URLVariables("targetTypeName="+targetTypeName.text+"&targetCal="+targetCal.text+"&temp="+Math.random());
var r:URLRequest=new URLRequest();
r.url=mainApp.urls+"/addTargetCal.do";
r.method=URLRequestMethod.POST;
r.data=v;
var l:URLLoader=new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,comp);
}else{
Alert.show("新增失败");
}
}
private function comp(e:Event):void{
var l:URLLoader = URLLoader(e.target);
var o:Object=URLUtil.stringToObject(l.data,";",true);
if(o.result=="add"){
Alert.show("新增成功");
var obj:Object=(JSON.decode(o.datas) as Object);
//dataArray.addItemAt(obj,0);
Alert.show(obj.targetCalId);
}
initComponent();
}
private function myClick(evt:CloseEvent):void{
//Alert.show("本次要删除的为"+mainDataGrid.selectedIndex);
if(evt.detail==Alert.YES){
//Alert.show(acItemsSelected.getItemAt(0).targetId);
var v:URLVariables = new URLVariables("id="+acItemsSelected.targetCalId+"&temp="+Math.random());
var r:URLRequest = new URLRequest();
r.url =mainApp.urls+"/deleteTargetCal.do" ;
r.method = URLRequestMethod.POST;
r.data=v;
var l:URLLoader = new URLLoader();
l.load(r);
//dataArray.removeItemAt(myGrid.selectedIndex);
l.addEventListener(Event.COMPLETE,comp1); //注册请求完成后 响应获取数据事件方法
}
}
private function comp1(e:Event):void
{
var l:URLLoader = URLLoader(e.target);
var o:Object = URLUtil.stringToObject(l.data, ";", true);
if(o.result=="delete"){
Alert.show("删除成功!","友情提示");
}
initComponent();
}
protected function button3_clickHandler(event:MouseEvent):void
{
if(myGrid.selectedItem==null){
Alert.show("请选择一项进行删除","友情提示");
}else{
var dlg_obj:Object=Alert.show("确认删除吗?", "友情提示!", Alert.YES|Alert.NO,null,myClick);
}
}
protected function button4_clickHandler(event:MouseEvent):void
{
if(myGrid.selectedItem==null){
Alert.show("请选择一项进行修订!","友情提示");
}else{
var v:URLVariables = new URLVariables("targetTypeName="+targetTypeName.text+"&targetCal="+targetCal.text+"&id="+acItemsSelected.targetCalId);
var r:URLRequest = new URLRequest();
r.url =mainApp.urls+"/updateTargetCal.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,comp3); //注册请求完成后 响应获取数据事件方法
}
}
private function comp3(e:Event):void
{
var l:URLLoader = URLLoader(e.target);
var o:Object = URLUtil.stringToObject(l.data, ";", true);
if(o.result=="update"){
Alert.show("更新成功!","友情提示");
var obj:Object=(JSON.decode(o.datas) as Object);
//dataArray.setItemAt(obj,myGrid.selectedIndex);
}else{
Alert.show("操作失败!","友情提示");
}
initComponent();
}
protected function myGrid_itemClickHandler(event:ListEvent):void
{
acItemsSelected =myGrid.selectedItem;
}
]]>
</fx:Script>
<mx:Form width="651" height="282">
<mx:DataGrid width="616" height="160" id="myGrid" itemClick="myGrid_itemClickHandler(event)">
<mx:columns>
<mx:DataGridColumn headerText="计量名称" dataField="targetTypeName"/>
<mx:DataGridColumn headerText="计量符号" dataField="targetCal"/>
<mx:DataGridColumn visible="false" dataField="targetCalId" />
</mx:columns>
</mx:DataGrid>
<mx:HBox>
<s:Label width="33"/>
<mx:FormItem label="计量名称" >
<s:TextInput id="targetTypeName"/>
</mx:FormItem>
<mx:FormItem label="计量符号" >
<s:TextInput id="targetCal"/>
</mx:FormItem>
<mx:FormItem >
<s:Button label="新增" id="myButton" click="button2_clickHandler(event)" />
</mx:FormItem>
</mx:HBox>
<mx:FormItem >
</mx:FormItem>
<mx:HBox>
<s:Label width="250"/>
<mx:FormItem >
<s:Button label="删除" click="button3_clickHandler(event)"/>
</mx:FormItem>
<mx:FormItem >
<s:Button label="修改" click="button4_clickHandler(event)"/>
</mx:FormItem>
<mx:FormItem >
<s:Button label="刷新"/>
</mx:FormItem>
<mx:FormItem >
<s:Button label="关闭" click="button1_clickHandler(event)"/>
</mx:FormItem>
</mx:HBox>
</mx:Form>
</s:TitleWindow>
关于上面这个程序的mainApp就不用管它,它只是主应用程序而已,细心的可以发现这个是个弹出窗口程序
关于这个程序的三个Servletet处理类【只贴上关键代码】
FindTargetCalServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
TTargetCalDAO dao=new TTargetCalDAO();
List<TTargetCal> cals=dao.findAll();
JSONArray json = JSONArray.fromObject(cals);
String datas = json.toString();
System.out.println(datas);
System.out.println(datas);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(datas);
}
DeleteTargetCalServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
TTargetCalDAO dao = new TTargetCalDAO();
String id = request.getParameter("id");
if (DataOptUtils.isNotNull(id)) {
TTargetCal rr = dao.findById(Integer.valueOf(id));
dao.delete(rr);
}
response.setCharacterEncoding("UTF-8");
response.getWriter().write("result=delete");
}
AddTargetCalServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
TTargetCalDAO dao=new TTargetCalDAO();
String targetCal=request.getParameter("targetCal");
String targetTypeName=request.getParameter("targetTypeName");
TTargetCal cal=new TTargetCal();
cal.setTargetCal(targetCal);
cal.setTargetTypeName(targetTypeName);
dao.save(cal);
TTargetCal re =dao.findById(dao.findLastId());
JSONObject json = JSONObject.fromObject(re);
String datas = json.toString();
response.getWriter().write("result=add;datas=" + datas);
}
UpdateTargetCalServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
TTargetCalDAO dao = new TTargetCalDAO();
String targetTypeName = request.getParameter("targetTypeName");
String targetCal = request.getParameter("targetCal");
String id = request.getParameter("id");
if (DataOptUtils.isNotNull(id)) {
TTargetCal rr = dao.findById(Integer.valueOf(id));
if(DataOptUtils.isNotNull(targetCal)){
rr.setTargetCal(targetCal);
}
if(DataOptUtils.isNotNull(targetTypeName)){
rr.setTargetTypeName(targetTypeName);
}
dao.merge(rr);
TTargetCal tc = dao.findById(rr.getTargetCalId());
JSONObject json = JSONObject.fromObject(tc);
String datas = json.toString();
response.getWriter().write("result=update;datas=" + datas);
}
}
这里的DataOptUtils是我写的一个数据处理类,判断是否为空什么的
还有就是TTargetCal
@Entity
@Table(name = "t_target_cal", catalog = "sxtele")
public class TTargetCal implements java.io.Serializable {
// Fields
private Integer targetCalId;
private String targetCal;
private String targetTypeName;
// Constructors
/** default constructor */
public TTargetCal() {
}
/** minimal constructor */
public TTargetCal(String targetCal) {
this.targetCal = targetCal;
}
/** full constructor */
public TTargetCal(String targetCal, String targetTypeName) {
this.targetCal = targetCal;
this.targetTypeName = targetTypeName;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "Target_cal_id", unique = true, nullable = false)
public Integer getTargetCalId() {
return this.targetCalId;
}
public void setTargetCalId(Integer targetCalId) {
this.targetCalId = targetCalId;
}
@Column(name = "Target_cal", nullable = false, length = 50)
public String getTargetCal() {
return this.targetCal;
}
public void setTargetCal(String targetCal) {
this.targetCal = targetCal;
}
@Column(name = "Target_type_name", length = 50)
public String getTargetTypeName() {
return this.targetTypeName;
}
public void setTargetTypeName(String targetTypeName) {
this.targetTypeName = targetTypeName;
}
}
已有 0 人发表留言,猛击->> 这里<<-参与讨论
JavaEye推荐
* 上海:高薪诚聘Python开发人员
* 北京:手机之家网站诚聘PHP程序员
阅读全文...
本站相关内容:
Flex4之Tree开发【三】——与JAVA后台交互的树,实现增删改查
今天的第三篇文章,把我两天学习的Flex4树的最重要的与实际开发相关的示例总结一下,实现与JAVA后台交互操作也就是增删改功能
第一:首先是MXML主要代码
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%"
creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.utils.URLUtil;
protected function init():void{
listResult.convertDataToXml();
}
var xmlList:XML;
protected function listResult_resultHandler(event:ResultEvent):void
{
xmlList=XML(event.result.toString());
mytree.dataProvider=xmlList;
}
protected function tree1_clickHandler(event:MouseEvent):void
{
if(mytree.selectedItem.hasOwnProperty("@value" ))
{
var u:URLRequest=new URLRequest(mytree.selectedItem.@value);
//navigateToURL(new URLRequest(mytree.selectedItem.@value));
navigateToURL(u);
} else
{
//没有那就展开,如果展开了就收缩
mytree.expandItem(mytree.selectedItem,!mytree.isItemOpen(mytree.selectedItem),true);
}
}
var child:XML;
//添加兄弟节点
protected function addBefore():void
{
var xml:XML=mytree.selectedItem as XML;
var text:String=nextName.text;
if(xml!=null && text.length>0) {
var parent:XML=xml.parent();
if(parent!=null) {
child=new XML("<node foddersortName=\"\" foddersortId=\"\" parentid=\"\" />");
child.@foddersortName=text;
parent.insertChildBefore(xml,child);
var v:URLVariables = new URLVariables("method=add&editName="+text+"&parentId="+parent.@foddersortId);
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url = "http://localhost:8080/FlexBlazeDS/treeOperate.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler);
} else {
Alert.show("不能选中根节点");
}
} else {
Alert.show("需要先选中节点和填入文字");
}
}
private function txtCompleteHandler(e:Event):void
{
var l:URLLoader = URLLoader(e.target);
var o:Object = URLUtil.stringToObject(l.data,";",true);
var result:String=o.result;
var operateId:String=o.operateId;
if(operateId!=null){
//Alert.show(o.operateId);
//每次添加完毕节点后,就需要将刚插入数据库中的最大的ID查询出来赋给刚刚新增的XML节点的属性中
child.@foddersortId=operateId;
}
if(result=="update"){
Alert.show("更新成功!");
}else if(result=="delete"){
Alert.show("删除成功!");
}else if(result=="add"){
Alert.show("新增成功!");
}else{
Alert.show("操作失败!");
}
}
protected function addAfter():void
{
var xml:XML=mytree.selectedItem as XML;
var text:String=nextName.text;
if(xml!=null && text.length>0) {
var parent:XML=xml.parent();
if(parent!=null) {
child=new XML("<node foddersortName=\"\" foddersortId=\"\" parentid=\"\" />");
child.@foddersortName=text;
parent.insertChildAfter(xml,child);
var v:URLVariables = new URLVariables("method=add&editName="+text+"&parentId="+parent.@foddersortId);
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url = "http://localhost:8080/FlexBlazeDS/treeOperate.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler);
} else {
Alert.show("不能选中根节点");
}
} else {
Alert.show("需要先选中节点和填入文字");
}
}
protected function addSon():void
{
var xml:XML=mytree.selectedItem as XML;
var text:String=nextName.text;
if(xml!=null && text.length>0) {
var parent:XML=xml.parent();
child=new XML("<node foddersortName=\"\" foddersortId=\"\" parentid=\"\" />");
child.@foddersortName=text;
xml.appendChild(child);
mytree.expandChildrenOf(xml,true);
var v:URLVariables = new URLVariables("method=add&editName="+text+"&parentId="+xml.@foddersortId);
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url = "http://localhost:8080/FlexBlazeDS/treeOperate.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler);
} else {
Alert.show("需要先选中节点和填入文字");
}
}
protected function editNode():void
{
var xml:XML=mytree.selectedItem as XML;
var text:String=nextName.text;
if(xml!=null && text.length>0) {
xml.@foddersortName=text;
} else {
Alert.show("需要先选中节点和填入文字");
}
var v:URLVariables = new URLVariables("method=update&editName="+text+"&parentId="+xml.@foddersortId);
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url = "http://localhost:8080/FlexBlazeDS/treeOperate.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler);
}
protected function deleteNode():void
{
var xml:XML=mytree.selectedItem as XML;
if(xml!=null) {
var list:Array=mytree.selectedItems as Array;
for(var k:int=0;k<list.length;k++) {
xml=list[k] as XML;
var parent:XML=xml.parent();
if(parent!=null) {
var children:XMLList=parent.children();
for(var i:int=0;i<children.length();i++) {
if(children[i]==xml) {
delete children[i];
var v:URLVariables = new URLVariables("method=delete&parentId="+xml.@foddersortId);
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url = "http://localhost:8080/FlexBlazeDS/treeOperate.do";
r.method = URLRequestMethod.POST;
r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler);
break;
}
}
} else {
Alert.show("不能选中根节点");
}
}
} else {
Alert.show("需要先选中节点");
}
}
protected function selectNode():void
{
var text:String=nextName.text;
if(text.length>0) {
var items:Array=[];
var list:XMLList=new XMLList();
list[0]=mytree.dataProvider[0];
searchItems(list,text,items);
mytree.selectedItems=items;
} else {
Alert.show("输入查找的文字");
}
}
private function searchItems(list:XMLList,find:String,items:Array):void {
for(var i:int=0;i<list.length();i++) {
var one:XML=list[i];
var label:String=one.@foddersortName;
if(label!=null && label.indexOf(find)>=0) {
items.push(one);
}
searchItems(one.children(),find,items);
}
}
protected function closeAll():void{
mytree.openItems=[];
}
protected function openAll():void{
mytree.expandChildrenOf(mytree.selectedItem,true);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
<s:RemoteObject destination="findName" id="listResult" result="listResult_resultHandler(event)"/>
</fx:Declarations>
<s:TextInput id="nextName" x="432" y="40" />
<mx:Tree x="30" y="10" width="264" height="600" id="mytree" showRoot="false" labelField="@foddersortName" ></mx:Tree>
<s:Button x="443" y="82" label="增加为哥" click="addBefore()"/>
<s:Button x="443" y="111" label="增加为弟" click="addAfter()"/>
<s:Button x="444" y="144" click="addSon()" label="增加为孩子"/>
<s:Button x="444" y="178" click="editNode()" label="修改节点"/>
<s:Button x="444" y="211" click="deleteNode()" label="删除节点"/>
<s:Button x="443" y="244" click="selectNode()" label="选择节点"/>
<s:Button x="443" y="277" click="closeAll()" label="全部收缩"/>
<s:Button x="443" y="306" click="openAll()" label="全部展开"/>
</s:Group>
这里写的是组件形式,在主程序中调用下文件名,如这个叫做FlexTree.mxml,其位于components目录下
那么在主程序中应该这样写
<components:FlexTree/>
就是这么一小行代码就可以执行主程序显示树了
第二:web-info/flex/remoteConfig.xml中关键配置
<destination id="findName" >
<properties>
<source>com.jadetrust.test.FindTreeNode</source>
</properties>
</destination>
第三:后台两个主要处理程序,一个是用来查询所有树节点拼装XML的程序FindTreeNode.java
//把数据库中的无限级联表中数据拼装成一个XML文档
public String convertDataToXml()
{
UserService sf=new UserService();
List<TCategory> cates=sf.findCategoriesAll();
System.out.println(cates);
List<TCategory> listTop=sf.findCategoriesTop();
String treedata="<?xml version='1.0' encoding='utf-8'?>\n<node foddersortId='0' foddersortName='所有分类'>\n";
for(TCategory cate:listTop){
treedata=treedata+"<node foddersortId='"+cate.getCateId() +"' foddersortName='"+cate.getName()+"'>\n";
treedata=CreateXmlNode(cates,cate.getCateId(),treedata);
treedata=treedata+"</node>\n";
}
treedata=treedata+"</node>\n";
System.out.println(treedata);
return treedata;
}
/**
* 递归解析list –> Xml
*/
public String CreateXmlNode(List<TCategory> list,int nodepid,String cratedata){
for (int a=0;a<list.size();a++)
{
TCategory cate=list.get(a);
if(cate.getTCategory()==null || cate.getTCategory().equals("")){
}else{
if (cate.getTCategory().getCateId()==nodepid){
if(cate.getTCategories()!=null){
cratedata=cratedata+"<node foddersortId='"+cate.getCateId() +"' foddersortName='"+cate.getName()+"' parentid='"+cate.getTCategory().getCateId()+"'>\n";
cratedata=CreateXmlNode(list,cate.getCateId(),cratedata);
cratedata=cratedata+"</node>\n";
}else{
cratedata=cratedata+"<node foddersortId='"+cate.getCateId()+"'foddersortName='"+cate.getName()+"' parentid='"+cate.getTCategory().getCateId()+"'/>\n";
}
}
}
}
return cratedata;
}
还有一个处理增删改的servleet程序
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("执行了树操作。。。。。。。。。。。。。。。");
request.setCharacterEncoding("utf-8");
String childName=request.getParameter("editName");
String parentId=request.getParameter("parentId");
String method=request.getParameter("method");
UserService sf=new UserService();
response.setCharacterEncoding("utf-8");
try{
if(method.equals("delete")){
System.out.println("此次删除的ID为"+parentId);
if(parentId!=null){
TCategory cate1=sf.findById(parentId);
System.out.println(cate1);
sf.delete(cate1);
response.getWriter().write("result=delete");
}
}else if(method.equals("update")){
System.out.println("此次更新的ID为"+parentId);
if(childName!=null&&parentId!=null){
TCategory cate1=sf.findById(parentId);
cate1.setName(childName);
System.out.println(cate1);
sf.update(cate1);
response.getWriter().write("result=update");
}
}else if(method.equals("add")){
if(childName!=null&&parentId!=null){
TCategory category=new TCategory();
category.setName(childName);
TCategory cate1=sf.findById(parentId);
category.setTCategory(cate1);
sf.add(category);
Integer lastId=sf.findLastId();
response.getWriter().write("result=add;operateId="+lastId);
}
}
}catch(Exception e){
System.out.println(e.toString());
response.getWriter().write("result=error");
}
}
第三,就是介绍相关的数据库表的结构了MYSQL
CREATE TABLE `t_category` (
`name` varchar(255) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`cate_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`cate_id`),
KEY `parent_id` (`parent_id`),
CONSTRAINT `t_category_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `t_category` (`cate_id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8;
对应的Category实体类
package com.jadetrust.dao;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* TCategory entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "t_category", catalog = "test")
public class TCategory implements java.io.Serializable {
// Fields
@Override
public String toString() {
return "[ cateId=" + cateId + ", name=" + name + "]";
}
private Integer cateId;
private TCategory TCategory;
private String name;
private Set<TCategory> TCategories = new HashSet<TCategory>(0);
// Constructors
/** default constructor */
public TCategory() {
}
/** full constructor */
public TCategory(TCategory TCategory, String name,
Set<TCategory> TCategories) {
this.TCategory = TCategory;
this.name = name;
this.TCategories = TCategories;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "cate_id", unique = true, nullable = false)
public Integer getCateId() {
return this.cateId;
}
public void setCateId(Integer cateId) {
this.cateId = cateId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
public TCategory getTCategory() {
return this.TCategory;
}
public void setTCategory(TCategory TCategory) {
this.TCategory = TCategory;
}
@Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "TCategory")
public Set<TCategory> getTCategories() {
return this.TCategories;
}
public void setTCategories(Set<TCategory> TCategories) {
this.TCategories = TCategories;
}
}
第四:具体数据库操作类UserService
package com.jadetrust.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.jadetrust.common.HibernateSessionFactory;
import com.jadetrust.dao.TCategory;
public class UserService {
public void add(TCategory cate){
Session session=HibernateSessionFactory.getSession();
Transaction tc=session.beginTransaction();
session.save(cate);
tc.commit();
session.close();
}
public void delete(TCategory cate){
Session session=HibernateSessionFactory.getSession();
Transaction tc=session.beginTransaction();
session.delete(cate);
tc.commit();
session.close();
}
public void update(TCategory cate){
Session session=HibernateSessionFactory.getSession();
Transaction tc=session.beginTransaction();
session.merge(cate);
tc.commit();
session.close();
}
public TCategory findById(String id){
String hql = "from TCategory where cateId=:id";
return (TCategory)HibernateSessionFactory.getSession().createQuery(hql).setString("id", id).uniqueResult();
}
public List<TCategory> findChildCategories(String id) {
if(id.equals("cate_root")||id==null||id.equals(" ")){
return findCategoriesTop();
}else{
return HibernateSessionFactory.getSession().
createQuery("from TCategory cate where cate.TCategory.cateId=:id").setString("id", id).list();
}
}
public List<TCategory> findCategoriesTop() {
System.out.println("查询顶级父目录.................");
String hql = "select distinct cate,childs from TCategory cate left join fetch cate.TCategories childs where cate.TCategory.cateId is null";
return HibernateSessionFactory.getSession().createQuery(hql).list();
}
public List<TCategory> findCategoriesAll() {
System.out.println("查询顶级父目录.................");
String hql = "from TCategory";
return HibernateSessionFactory.getSession().createQuery(hql).list();
}
public List<Map<String,String>> findNameById(String id){
List<Map<String,String>> names=new ArrayList<Map<String,String>>();
UserService sf=new UserService();
Set<TCategory> cates=sf.findById(id).getTCategories();
for(TCategory cate:cates){
Map<String,String> maps=new HashMap<String,String>();
maps.put("CATALOGSID", cate.getCateId().toString());
maps.put("CATALOGNAME", cate.getName());
names.add(maps);
}
return names;
}
public Integer findLastId(){
String hql="select max(cateId) from TCategory";
return (Integer)HibernateSessionFactory.getSession().createQuery(hql).uniqueResult();
}
}
这个示例只用了Hibernate,至于这个HibernateSessionFactory,它是利用MyEclipse反转数据库自动生成的,如果不知道可以参考我之前关于数据库反转的文章
相关视图
这个是选择节点,输入插入内容,点击选择节点按钮
已有 0 人发表留言,猛击->> 这里<<-参与讨论
JavaEye推荐
* 北京:手机之家网站诚聘PHP程序员
* 上海:高薪诚聘Python开发人员
Flex4之DataGrid四个的示例【客户端和服务器端】
由于我的DataGrid与JAVA后台交互需要返回JSON格式的字符串,所以需要在客户端来解析JSON串,用到JSON相关类,所以Flex4还缺少一个文件corelib.swc
将corelib.swc拷贝到Flex安装目录的sdks\4.0.0\frameworks\libs下
这个文件导入后重启MyEclipse就可以使用JSON类了
1,客户端、服务端
(1)客户端分页:将数据一次性取到客户端,客户要看哪一页的数据,显示哪一页的数据。
(2)服务端分页:客户要看哪一页的数据,向服务端请求哪一页的数据,客户端将请求到的数据显示给用户(可以在客户端、服务端分别做缓存,加快数据的读取),由于flex本身不具有数据库访问能力,可以考虑通过 WebServices向服务器传递数据,数据的表示形式可以是XML、JSON(本文采用XML的形式)
2,分页表示层的设计
(1)页码条中4个按钮;这四个按钮分别为转到第一页,前一页,后一页,最后一页;当这四个按钮中的任意一点被点击时,页码要重绘,当前页码变化;且还要考虑当页码中有第一页时,前两个按钮要隐藏起来;当页码中有最后一页时,后两个按钮要隐藏起来。
(2)页码条中页码;当点击页码条中的页码时,DataGrid中更新显示数据即可,当前页码变化。
(3)显示总页数,总记录数;
(4)每页记录数,让用户通过下拉框选择;当用户选择新的每页显示记录数时,页码要重绘,总页数发生变化,当前页码变化。
(5)页码输入框,让用户输入任意页码(要检查输入数据是否合法),DataGrid显示页码中的数据,页码要重绘,总页数变化。
(6)查看所有;分页中的特殊情况,将每页记数置为记录总数即可达到要求!页码要重绘,总页数发生变化,当前页码变化
代码说明
(1)分页功能条,做一个自定义组件
(2)页码条绘制方法,传参数为页码中的第一个页码
3.分页触发的方法,组件中有一个属性为pagingFunction,为向服务端请求数据的函数;当该函数为空时,调用客户端分页;反之调用该方法进行服务端分页。
首先说明下:以下的四个例子中每一个都含有客户端获取DataGrid数据的代码
下面的每个mxml中都涉及用到的组件mxml,位于com/control目录下
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.ItemClickEvent;
import flash.events.KeyboardEvent;
import mx.controls.DataGrid;
import mx.validators.NumberValidator;
[Bindable]
[Embed(source='assets/first.jpg')]
private var firstIcon:Class;
private var firstPage:uint;
[Bindable]
[Embed(source='assets/pre.jpg')]
private var preIcon:Class;
private var prePage:uint;
[Bindable]
[Embed(source='assets/next.jpg')]
private var nextIcon:Class;
private var nextPage:uint;
[Bindable]
[Embed(source='assets/last.jpg')]
private var lastIcon:Class;
private var lastPage:uint;
//页码条数据,绑定
[Bindable]
private var nav:ArrayCollection = new ArrayCollection();
//默认起始页码,第1页
private var currentPageIndex:uint = 0;
//是否已初始化
private var isInit:Boolean=true;
//总页数
private var totalPages:uint = 0;
//是否重绘页码条,当使用服务端分页时使用
private var isCreateNavBar:Boolean = true;
/************************************************************/
//显示到Grid的数据
[Bindable]
public var viewData:ArrayCollection=null;
//所有的数据
public var orgData:ArrayCollection=null;
//每页记录数下拉框
public var pageSizeDropDownListData:ArrayCollection=null;
// 每页记录数
public var pageSize:uint = 5;
// 页码条上显示页码的个数
public var navSize:uint = 5;
//记录总数,调用服务端发页时使用
public var totalRecord:int=0;
//分页函数
public var pagingFunction:Function=null;
//分页条对应的Grid
public var dataGrid:DataGrid=null;
/***************************************************************/
public function dataBind(isServerSide:Boolean=false):void{
//是否初始化
if(isInit){
if(pageSizeDropDownListData==null){
pageSizeDropDownListData = new ArrayCollection();
pageSizeDropDownListData.addItem({label:5,data:5});
pageSizeDropDownListData.addItem({label:10,data:10});
pageSizeDropDownListData.addItem({label:20,data:20});
pageSizeDropDownListData.addItem({label:30,data:30});
}
pageSizeComobox.dataProvider=pageSizeDropDownListData;
isInit=false;
}
//
refreshDataProvider(currentPageIndex,isCreateNavBar,pageSize,isServerSide);
}
/**
* 构建页码条
* pages:总页数
* pageIndex:当前页(注意,从0开始)
*
*/
private function createNavBar(pageIndex:uint = 0):void{
nav.removeAll();
//向前图标操作,first,Pre
if( pageIndex > 1 ){
firstPage=0;
firstNavBtn.visible=true;
//
var intLFive:int = pageIndex-navSize; // calculate start of last 5;
//
prePage=intLFive;
preNavBtn.visible=true;
}
else{
firstNavBtn.visible=false;
preNavBtn.visible=false;
}
//页码条
for( var x:uint = 0; x < navSize; x++){
var pg:uint = x + pageIndex;
nav.addItem({label: pg + 1,data: pg});
//
var pgg:uint = pg+1;
if(pgg>=totalPages){ //搜索到最后一个页码,停止添加到navbar
x=navSize;
}
}
//计算最后一组页码条中第一个页码的页码编号
var lastpage:Number = 0;
for( var y:uint = navSize; y <= totalPages-1;y = y + navSize ){ //lets calculate the lastpage button
if(y+5 > navSize){
lastpage = y;
}
}
//向后图标
if( pg < totalPages - 1 ){
nextPage=pg + 1;
nextNavBtn.visible=true;
lastPage=lastpage;
lastNavBtn.visible=true;
}
else{
nextNavBtn.visible=false;
lastNavBtn.visible=false;
}
}
/**
* 页码按钮按下(页码条点击)
*/
private function navigatePage(event:ItemClickEvent):void
{
refreshDataProvider(event.item.data,false);
}
/**
* 页码按钮按下,first,pre,next,last
*/
private function navigateButtonClick(pageString:String):void{
var pageIndex:uint=0;
switch(pageString){
case "firstPage":
pageIndex=firstPage;
break;
case "prePage":
pageIndex=prePage;
break;
case "nextPage":
pageIndex=nextPage;
break;
default: //lastPage
pageIndex=lastPage;
}
//
refreshDataProvider(pageIndex);
}
/**
* 更新数据源,更新表格显示数据
*/
private function refreshDataProvider(pageIndex:uint,isCreateNavBar:Boolean=true,pageSize:uint=0,resultReturn:Boolean=false):void{
//分页函数
if(dataGrid==null) return;
currentPageIndex=pageIndex;
if(pageSize==0){
pageSize=this.pageSize;
}else{
this.pageSize=pageSize;
if(!resultReturn) totalPages = Math.ceil(orgData.length/pageSize);
}
if(!resultReturn){
if(this.pagingFunction!=null){
pagingFunction(pageIndex,pageSize);
this.isCreateNavBar=isCreateNavBar;
}
else{
viewData = new ArrayCollection( orgData.source.slice((pageIndex * pageSize),(pageIndex * pageSize) + pageSize) );
dataGrid.dataProvider=viewData;
pageNumber.text=(pageIndex+1).toString();
totalRecordLabel.text = '总记录数:' + orgData.length.toString();
}
}
else{
dataGrid.dataProvider=orgData;
totalPages = Math.ceil(totalRecord/pageSize);
pageNumber.text=(pageIndex+1).toString();
totalRecordLabel.text = '总记录数:' + totalRecord.toString()
}
totalPagesLabel.text = '总页数:' + totalPages;
if(isCreateNavBar) createNavBar(pageIndex);
}
//
/**
* 每页记录数变更(下拉框选择)
*/
private function pageSizeSelectChange():void{
refreshDataProvider(0,true,uint(pageSizeComobox.value));
}
/**
* 页码变更(直接输入)
*/
private function pageIndexInsertChange(event:Event):void{
var keyboardEvent:KeyboardEvent=event as KeyboardEvent;
if(keyboardEvent!=null&&keyboardEvent.keyCode== Keyboard.ENTER){
var pageIndex:uint=uint(pageNumber.text)-1;
if(pageIndex>0&&pageIndex<totalPages&&pageIndex!=currentPageIndex){
refreshDataProvider(pageIndex);
}
else{
pageNumber.text = (currentPageIndex+1).toString();
}
}
}
/**
* 查看所有
*/
private function viewAll():void{
var tempTotalRecord:uint=0;
if(pagingFunction!=null) tempTotalRecord=totalRecord;
else tempTotalRecord=orgData.length;
//
pageSizeComobox.text=tempTotalRecord.toString();
pageSizeComobox.selectedIndex=-1;
refreshDataProvider(0,true,tempTotalRecord);
}
]]>
</mx:Script>
<mx:HBox paddingTop="8">
<mx:Button id="firstNavBtn" icon="{firstIcon}" width="10" height="10" click="navigateButtonClick('firstPage');" />
<mx:Button id="preNavBtn" icon="{preIcon}" width="7" height="10" click="navigateButtonClick('prePage');"/>
</mx:HBox>
<mx:LinkBar id="pageNav" itemClick="navigatePage(event)" dataProvider="{nav}"/>
<mx:HBox paddingTop="8">
<mx:Button id="nextNavBtn" icon="{nextIcon}" width="7" height="10" click="navigateButtonClick('nextPage');"/>
<mx:Button id="lastNavBtn" icon="{lastIcon}" width="10" height="10" click="navigateButtonClick('lastPage');"/>
</mx:HBox>
<mx:VRule height="25"/>
<mx:Label paddingTop="3" id="totalPagesLabel" text=""/>
<mx:Label paddingTop="3" id="totalRecordLabel" text=""/>
<mx:Label paddingTop="3" text="每页记录:"/>
<mx:ComboBox id="pageSizeComobox" cornerRadius="0" paddingLeft="0" fontWeight="normal" width="50" arrowButtonWidth="10" change="pageSizeSelectChange()"/>
<mx:Label paddingTop="3" text="页码:"/>
<mx:TextInput id="pageNumber" width="40" keyDown="pageIndexInsertChange(event);"/>
<mx:LinkButton id="viewAllLinkBtn" label="查看所有" click="viewAll();"/>
</mx:HBox>
第一: HTTPService获取服务器端数据显示DataGrid
HTTPService的方式一
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();myservice.send()"
minWidth="955" minHeight="600">
<fx:Style>
Application{
fontSize:12;
}
</fx:Style>
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 这个HTTPService使用时一定要提前调用send方法-->
<s:HTTPService id="myservice" url="http://localhost:8080/ClientServerDataGrid/find.do" result="myservice_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();
}
protected function myservice_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>
HTTPService的方式二
<?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>
<!-- 将非可视元素(例如服务、值对象)放在此处 这个HTTPService使用时一定要提前调用send方法-->
<s:HTTPService id="myservice" />
</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;
import mx.utils.URLUtil;
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();
myservice.url="http://localhost:8080/ClientServerDataGrid/find.do";
myservice.showBusyCursor=true;
myservice.send();
myservice.addEventListener(ResultEvent.RESULT,hsResultHandler);
myservice.addEventListener(FaultEvent.FAULT,hsFaultHandler);
}
private function hsResultHandler(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();
}
private function hsFaultHandler(e:FaultEvent):void{
Alert.show(e.fault.toString(),'http请求错误');
}
]]>
</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>
第二:URLRequest方式获取
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>
<!-- 将非可视元素(例如服务、值对象)放在此处 这个HTTPService使用时一定要提前调用send方法-->
</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;
import mx.utils.URLUtil;
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();
//var v:URLVariables = new URLVariables("name=jacky&age=35&address=HongKong China");
/*
也可以是这种方式
var vars: URLVariables = new URLVariables ();
vars["varName"] = varValue; //把参数键,值对放到vars对象中.
vars["var2Name"] = var2Value;
*/
var r:URLRequest = new URLRequest();
r.url ="http://localhost:8080/ClientServerDataGrid/find.do";
r.method = URLRequestMethod.POST;
//r.data = v;
var l:URLLoader = new URLLoader();
l.load(r);
l.addEventListener(Event.COMPLETE,txtCompleteHandler); //注册请求完成后 响应获取数据事件方法
}
private function txtCompleteHandler(e:Event):void
{
var l:URLLoader = URLLoader(e.target);
/* URLUtil的stringToObject方法解释
从字符串返回对象。字符串包含 name=value 对,它们成为返回对象的动态属性。这些属性对由指定的 separator 分隔。该方法可转换数字、布尔值、数组(由“[]”定义)以及子类(由“{}”定义)。默认情况下,%XX 格式的 URL 模式将转换为相应的字符串字符。
例如:
var s:String = "name=Alex;age=21";
var o:Object = URLUtil.stringToObject(s, ";", true);
返回对象:{ name: "Alex", age: 21 }。
*/
//直接获取返回值内容: URLLoader(e.target).data
// Alert.show(l.data);
// var o:Object = URLUtil.stringToObject(l.data,";",true); //使用URLUtil对将数据进行反序列化以方便使用
var rawData:String = String(l.data);
//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>
针对上面两种方式的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