今天的第三篇文章,把我两天学习的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反转数据库自动生成的,如果不知道可以参考我之前关于数据库反转的文章
相关视图