Flex与Java通信 BlazeDS方式 解析xml

Flex与java通信最简单例子(详细说明了各种需要注意的配置):http://blog.csdn.net/u010011052/article/details/9116869

Flex与java通信(java查询数据库返回List,Flex调用java展示数据):http://blog.csdn.net/u010011052/article/details/9116871

Flex与java通信(java解析xml返回List,Flex调用java展示数据):http://blog.csdn.net/u010011052/article/details/9127643

 

这个例子展示的意思是:

java解析xml 并返回一个比较复杂的实体对象集合;

然后Flex调用java类拿到对象集合进行遍历,

并将遍历出来的数据塞到一个新的ArrayCollection中,用DataGrid进行数据的展示。

这里的重点不在java,而是Flex的显示

 

1、java项目中(为树状xml设计的实体类

这个实体类稍显复杂,这样写是为了根节点能对应子节点,可能有更方便的写法,希望大家可以提出好的建议

package tobaccoTrans.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DWJ   
 */
public class UserNode implements Serializable {
	private String provinceId;
	private String provinceName;
	// key=proviceId  value=[cityid,cityname]
	private List<String[]> cities;
	// key=proviceId_cityId  value=[disId,disName]
	private Map<String,List<String[]>> disMap;
	// key=proviceId_cityId_disId  value=[nodeId,nodeName]
	private Map<String,List<String[]>> nodeMap;

	public String getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}

	public String getProvinceName() {
		return provinceName;
	}

	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}

	public List<String[]> getCities() {
		if (cities == null) {
			return new ArrayList<String[]>();
		}
		return cities;
	}

	public void setCities(List<String[]> cities) {
		this.cities = cities;
	}

	public Map<String,List<String[]>> getdisMap() {
		if (disMap == null) {
			return new HashMap<String,List<String[]>>();
		}
		return disMap;
	}

	public void setdisMap(Map<String,List<String[]>> disMap) {
		this.disMap = disMap;
	}

	public Map<String,List<String[]>> getNodeMap() {
		if (nodeMap == null) {
			return new HashMap<String,List<String[]>>();
		}
		return nodeMap;
	}

	public void setNodeMap(Map<String,List<String[]>> nodeMap) {
		this.nodeMap = nodeMap;
	}
}


2、java中的xml解析类

package tobaccoTrans.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import tobaccoTrans.entity.UserNode;
import tobaccoTrans.util.ReadStream;


/**
 * @author DWJ
 */
public class UserNodeImpl extends ReadStream{
	private Document document = null;

	/**
	 * @param user 用户  
	 * @param pwd 密码
	 * @return List<UserNode> 以实体对象为单位的数据集合 
	 * @throws DocumentException
	 * 解析xml文件存储到集合中
	 */
	public List getAllNodes(String user,String pwd){
		List<UserNode> list = new ArrayList<UserNode>();
		try {
			String path = "http://10.60.250.116/server/getnode.PHP?";  //内网地址
//			String path = "http://www.yancao18.com/server/getnode.PHP?"; //外网地址
			path += "user="+user+"&pwd="+pwd;
			document = this.Read(path.trim());
			Element root = document.getRootElement();
			
			//获取省份下各节点
			List<Node> nodes = root.selectNodes("/root/pnode/province");
			Iterator iter = nodes.iterator();
			while (iter.hasNext()) {
				UserNode provinceInfo = new UserNode();
				
				Map<String,List<String[]>> disMap = new HashMap<String,List<String[]>>();
				Map<String,List<String[]>> nodeMap = new HashMap<String,List<String[]>>();
				
				Element proviceElement = (Element) iter.next();
				String provinceId = proviceElement.elementText("pid");
				String provinceName = proviceElement.elementText("pname");
				provinceInfo.setProvinceId(provinceId);
				provinceInfo.setProvinceName(provinceName);
				
				//获取城市下各节点
				List<String[]> cityList = new ArrayList<String[]>();
				List<Node> cityNodes = proviceElement.selectNodes("cnode/city");
				Iterator cityIter = cityNodes.iterator();
				while (cityIter.hasNext()) {
					String[] cityInfo = new String[2];
					Element cityElement = (Element) cityIter.next();
					String cityId = cityElement.elementText("cid");
					String cityName = cityElement.elementText("cname");
					cityInfo[0] = cityId;
					cityInfo[1] = cityName;
					//获取区域下各节点
					List<String[]> disList = new ArrayList<String[]>();
					String disKey = provinceId + "_" + cityId;
					List<Node> disNodes = cityElement.selectNodes("znode/zone");
					Iterator disIter = disNodes.iterator();
					while (disIter.hasNext()) {
						String[] disInfo = new String[2];
						Element disElement = (Element) disIter.next();
						String disNodeId = disElement.elementText("zid");
						String disNodeName = disElement.elementText("zname");
						disInfo[0] = disNodeId;
						disInfo[1] = disNodeName;
						//获取各子节点
						List<String[]> nodeList = new ArrayList<String[]>();
						String nodeKey = provinceId + "_" + cityId + "_" + disNodeId;
						List<Node> nodeNodes = disElement.selectNodes("nnode/node");
						Iterator nodeIter = nodeNodes.iterator();
						while (nodeIter.hasNext()) {
							String[] nodeInfo = new String[3];
							Element nodeElement = (Element) nodeIter.next();
							String nodeNodeId = nodeElement.elementText("nid");
							String nodeNodeName = nodeElement.elementText("nname");
							String userId = nodeElement.elementText("userid");
							nodeInfo[0] = nodeNodeId;
							nodeInfo[1] = nodeNodeName;
							nodeInfo[2] = userId;
							nodeList.add(nodeInfo);
						}
						nodeMap.put(nodeKey,nodeList);
						disList.add(disInfo);
					}
					disMap.put(disKey,disList);
					cityList.add(cityInfo);
				}
				provinceInfo.setCities(cityList);
				provinceInfo.setdisMap(disMap);
				provinceInfo.setNodeMap(nodeMap);
				list.add(provinceInfo);
			}
		} catch (Exception e) {
			// Todo Auto-generated catch block
			e.printstacktrace();
		}
		return list;
	} 

}

 

下面是xml解析类继承的一个读取数据流类

package tobaccoTrans.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Document;
import org.dom4j.io.Domreader;

/**
 * @author DWJ
 */
public class ReadStream {
	public static Document Read(String str) {
		URL url;
		Document document = null;
		try {
			url = new URL(str);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(6 * 1000);// 设置连接超时
			if (conn.getResponseCode() != 200)throw new RuntimeException("请求rul失败!");
			InputStream inputStream = (InputStream) conn.getInputStream();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			org.w3c.dom.Document doc = db.parse(inputStream);
//			org.w3c.dom.Document doc = db.parse(new InputSource(new ByteArrayInputStream(inputStream.getBytes("utf-8"))));
			Domreader domreader = new Domreader();
			document = domreader.read((org.w3c.dom.Document) doc);
		} catch (Exception e) {
			// Todo Auto-generated catch block
			e.printstacktrace();
		}
		return document;
	}
}

 

3、remoting-config.xml 配置,更对详细配置请参照:http://blog.csdn.net/u010011052/article/details/9116869

<?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="UserNodeImpl">  
         <properties>  
              <source>tobaccoTrans.dao.impl.UserNodeImpl</source>
         </properties>  
    </destination> 
	
</service>

 

4、Flex项目中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" 
			   initialize="init()"
			   minWidth="955" minHeight="600">
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.events.FlexEvent;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			
			[Bindable]
			protected function init():void
			{
				// Todo Auto-generated method stub
				uni.getAllNodes("zhucheng","zhucheng");
			}
			
			[Bindable]
			var usernodeList:ArrayCollection = new ArrayCollection();
			var cities:ArrayCollection = new ArrayCollection();
			var newArray:ArrayCollection = new ArrayCollection(); //创建的一
			protected function uni_resultHandler(event:ResultEvent):void
			{
				// Todo Auto-generated method stub
				//获取省份
				usernodeList = event.result as ArrayCollection;
				var usernodeListLength:int = usernodeList.length;
				for(var iusernode:int = 0; iusernode < usernodeListLength; iusernode++){
					var pid:String   = usernodeList[iusernode].provinceId;     //要显示的:省份id
					var pname:String   = usernodeList[iusernode].provinceName; //要显示的:省份name
					newArray.addItem({pid:pid});
					newArray.addItem({pname:pname});
					
					//获取城市
					cities = usernodeList[iusernode].cities;//iusernode
					var citiesLength:int = cities.length;
					for(var icity:int = 0; icity < citiesLength; icity++){
						//cities[i]下2个子节点
						var cityid:String = cities[icity][0].toString();   //要显示的:城市id
						var cityname:String = cities[icity][1].toString(); //要显示的:城市name
						newArray.addItem({cityid:cityid});
						newArray.addItem({cityname:cityname});
						
						//获取区域
						var disKey:String = pid + "_" + cityid;
						var dismap:ArrayCollection = new ArrayCollection();
						dismap = usernodeList[iusernode].disMap[disKey];//iusernode
						var dismapLength:int = dismap.length;
						for(var idis:int = 0; idis < dismapLength; idis++){
							//dismap[i]下2个子节点
							var disid:String = dismap[idis][0];   //要显示的:区域id
							var disname:String = dismap[idis][1]; //要显示的:区域name
							newArray.addItem({disid:disid});
							newArray.addItem({disname:disname});
							
							//获取子节点
							var nodeKey:String = disKey + "_" + disid;
							var nodemap:ArrayCollection = new ArrayCollection();
							nodemap = usernodeList[iusernode].nodeMap[nodeKey];//iusernode
							var nodemapLength:int = nodemap.length;
							for(var inode:int = 0; inode < nodemapLength; inode++){
								//nodemap[i]下3个子节点
								var nodeid:String = nodemap[inode][0];   //要显示的:子节点id
								var nodename:String = nodemap[inode][1]; //要显示的:子节点name
								var userid:String = nodemap[inode][2];   //要显示的:userid
								newArray.addItem({nodeid:nodeid});
								newArray.addItem({nodename:nodename});
								newArray.addItem({userid:userid});
								
							} //获取子节点结束
							
						} //获取区域结束
						
					} //获取城市结束
					
				} //获取省份结束
				
			} //uni_resultHandler结束
			
			[Bindable]
			protected function uni_faultHandler(event:FaultEvent):void
			{
				// Todo Auto-generated method stub
				
			}
			
		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<s:RemoteObject id="uni" destination="UserNodeImpl" result="uni_resultHandler(event)" fault="uni_faultHandler(event)" />
	</fx:Declarations>
	<mx:Panel x="16" y="15" width="95%" height="95%" title="展示UserNode数据Panel">
		<mx:DataGrid x="15" y="15" width="92%" height="92%" id="dataGrid"  dataProvider="{newArray}">
			<mx:columns>
				<mx:DataGridColumn headerText="pid" datafield="pid" />
				<mx:DataGridColumn headerText="pname" datafield="pname" />
				<mx:DataGridColumn headerText="cid" datafield="cityid" />
				<mx:DataGridColumn headerText="cname" datafield="cityname" />
				<mx:DataGridColumn headerText="zid" datafield="disid" />
				<mx:DataGridColumn headerText="zname" datafield="disname" />
				<mx:DataGridColumn headerText="nid" datafield="nodeid" />
				<mx:DataGridColumn headerText="nname" datafield="nodename" />
				<mx:DataGridColumn headerText="userid" datafield="userid" />
			</mx:columns>
		</mx:DataGrid>
	</mx:Panel>
</s:Application>

注意:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

5、绑定好,运行mxml应用程序即可看到数据。

相关文章

一:display:flex布局display:flex是一种布局方式。它即可以...
1. flex设置元素垂直居中对齐在之前的一篇文章中记载过如何...
移动端开发知识点pc端软件和移动端apppc端软件是什么,有哪些...
最近挺忙的,准备考试,还有其他的事,没时间研究东西,快周...
display:flex;把容器设置为弹性盒模型(设置为弹性盒模型之后...
我在网页上运行了一个Flex应用程序,我想使用Command←组合键...