本例子实现与JAVA后台交互操作也就是增删改功能。主要知识点:XML的生成,hibernate的CURD,Tree控件。
1.Flex主程序
<?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" minWidth="955" minHeight="600" xmlns:components="components.*"> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <components:FlexTree/> </s:Application>
2.Flex控件:FlexTree.mxml包:components)
<?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/Flex02_Tree_Java/servlet/CURD"; 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/Flex02_Tree_Java/servlet/CURD"; 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/Flex02_Tree_Java/servlet/CURD"; 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/Flex02_Tree_Java/servlet/CURD"; 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/Flex02_Tree_Java/servlet/CURD"; 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>
3.JavaBean:TCategory.java
package com.wcx.bean; import java.util.HashSet; 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; @Entity @Table(name = "t_category") 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; } }
4.UserService.java
package com.wcx.service; 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.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import com.wcx.bean.TCategory; public class UserService { private SessionFactory sessionFactory = new AnnotationConfiguration() .configure().buildSessionFactory(); public void add(TCategory cate) { Session session = sessionFactory.openSession(); Transaction tc = session.beginTransaction(); session.save(cate); tc.commit(); System.out.println("数据库插入完成") ; session.close(); } public void delete(TCategory cate) { Session session = sessionFactory.openSession(); Transaction tc = session.beginTransaction(); session.delete(cate); tc.commit(); System.out.println("数据库删除完成") ; session.close(); } public void update(TCategory cate) { Session session = sessionFactory.openSession(); Transaction tc = session.beginTransaction(); session.merge(cate); tc.commit(); System.out.println("数据库更新完成") ; session.close(); } public TCategory findById(String id) { String hql = "from TCategory where cateId=:id"; return (TCategory) sessionFactory.openSession().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 (List<TCategory>)(sessionFactory.openSession().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 sessionFactory.openSession().createQuery(hql).list(); } public List<TCategory> findCategoriesAll() { System.out.println("查询所有的项目................."); String hql = "from TCategory"; return sessionFactory.openSession().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) sessionFactory.openSession().createQuery(hql) .uniqueResult(); } }
5.组装XML文件
package com.wcx.util; import java.util.List; import com.wcx.bean.TCategory; import com.wcx.service.UserService; public class FindTreeNode { // 把数据库中的无限级联表中数据拼装成一个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; } }
6.Servlet接受页面的请求
package com.wcx.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wcx.bean.TCategory; import com.wcx.service.UserService; public class CURD extends HttpServlet { public CURD() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log } 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"); } } public void init() throws ServletException { // Put your code here } }
7.remote-config配置文件
<destination id="findName" > <properties> <source>com.wcx.util.FindTreeNode</source> </properties> </destination>
8.数据库SQL语句
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;
相关推荐
本项目“flex+java实现增删改查Dome”是一个基于Flex前端和Java后端的示例,用于演示如何实现数据的CRUD(Create、Read、Update、Delete)操作。下面将详细介绍Flex与Java的集成以及在这个Dome中的具体应用。 Flex...
标题 "flex+java增删改查(spring+jpa)简单例子" 暗示了这是一个关于使用Adobe Flex作为前端UI框架,与Java后端结合,实现数据的CRUD(创建、读取、更新、删除)操作的教程。在这个场景中,Java后端使用Spring框架...
《Flex实战:PureMVC+Java(Spring+Hibernate)实现增删改查操作》 在本文中,我们将深入探讨如何利用Flex作为前端展示层,结合后端的Java技术栈,包括Spring和Hibernate,来构建一个完整的CRUD(创建、读取、更新、...
根据提供的信息,我们可以总结出以下相关的IT知识点: ...通过这种方式,Flex与Java能够很好地协同工作,共同实现数据的增删改查功能。此外,还需要考虑安全性问题,如数据加密、用户认证等,以确保应用程序的安全性。
ActionScript3 Flex初级入门,实现Flex增删改查,初级入门的Flex初级程序员可以看看
《FLEX最强增删改查》是一个综合性的示例项目,它涵盖了使用Flex、Spring、Hibernate和Java技术栈进行Web应用程序开发中的基本操作,包括数据的添加(Add)、删除(Delete)、修改(Update)和查询(Query)。...
### Flex通过Java实现增删改查 在软件开发过程中,增删改查(CRUD)操作是最基础也是最重要的数据操作之一。本文将详细介绍如何利用Java技术实现这些操作,并结合Flex前端技术来展示一个完整的示例。 #### 数据库...
在本压缩包中,"flex增删改查例子(完整版)"是一个示例项目,旨在帮助开发者了解如何在Flex中实现数据库操作的基本功能,包括添加(Add)、删除(Delete)、修改(Update)和查询(Query)数据。 1. **Flex基础...
### Flex操作XML实现增删改查 在Flex中操作XML数据是进行动态内容处理的关键技能之一。本篇文章将深入探讨如何使用Flex中的XML类来实现对XML数据的增、删、改、查功能。 #### 一、理解XML结构 XML(可扩展标记...
通过以上步骤,我们可以构建一个完整的Flex-BlazDS-Java集成应用,实现数据的增删改查功能。这个过程涉及到了前端UI设计、后端服务开发、数据访问以及错误处理等多个方面,对于理解和掌握Flex和BlazDS的集成技术非常...
本文将详细阐述如何通过BlazeDS这一中间件,实现Flex与Java的完美整合,以完成数据库的增删改查操作。 1. **BlazeDS介绍** BlazeDS是Adobe官方提供的一款开源服务器端组件,它允许Flex客户端与Java服务器进行实时...
### Flex与Java整合实现增删改查功能详解 在当今的软件开发领域,Flex与Java的结合被广泛应用于创建高效且交互丰富的应用。本文将基于提供的文档内容,深入解析Flex与Java整合过程中如何实现基本的数据库操作——增...
标题中的“flex访问netwebservice增删改查”指的是使用Adobe Flex作为前端开发工具,通过调用.NET(ASP.NET)创建的Web服务(Web Service)来实现对数据库的数据操作,包括增加(Add)、删除(Delete)、修改...
这个名为“flex_java_mysql 增删改查”的项目就是一个典型的三层架构示例,它结合了Adobe Flex作为前端、Java作为服务端后端以及MySQL作为数据库进行数据管理。以下是关于这三个关键技术的详细解释: 1. Flex:Flex...
综上所述,这个源码项目展示了如何综合运用Flex、LINQ、SQL Server 2005和Asp.net构建一个完整的Web应用程序,实现了数据的增删改查功能。通过学习这个项目,开发者可以深入理解这些技术的协同工作方式,提升在实际...
Flex与Java的交互是跨平台应用开发中的常见技术组合,允许前端用户界面(UI)与后端业务逻辑进行高效沟通。在本文中,我们将深入探讨如何使用Flex 4与Java进行通信,并通过三种不同的方法实现这一目标:RemoteObject...
本示例着重介绍如何在Flex中实现与后台系统的数据交互。 在Flex应用中,与后台交互通常涉及到网络通信,主要通过HTTPService、WebService或AMFChannel等组件来完成。HTTPService允许开发者发送HTTP请求到服务器,...