前期准备:
用到的工具:myeclipse 6.5 + flash builder 4.5 + blazeds3.3.0 + mysql数据库 + tomcat 6.0.20
blazeds下载 这个好像得注册个用户
https://www.adobe.com/cfusion/entitlement/index.cfm?e=lc_blazeds
----------------------------
效果展示:
----------------------------
具体实现:
1.java端准备
(1)用myeclipse创建web工程FlexTopTest
(2)将下载下来的blazeds-turnkey-3.3.0.22497.rar解压,将如下目录的内容
{blazeds-home}\tomcat\webapps\blazeds\WEB-INF
替换掉FlexTopTest中的WEB-INF中的内容
(3)具体编码实现,现把servlet端代码贴出来
UserService userService = new UserServiceImpl(); StringBuilder content = new StringBuilder(); String method = request.getParameter("method"); if("list".equals(method)) { String pageNo_str = request.getParameter("pageNo"); String pageSize_str = request.getParameter("pageSize"); String keyword = request.getParameter("keyword"); int pageNo = 1; int pageSize = 20; try { pageNo = Integer.parseInt(pageNo_str); pageSize = Integer.parseInt(pageSize_str); } catch (NumberFormatException e) { } // List<User> userList = userService.getList(pageNo, pageSize); // content.append(JsonUtils.toJson(userList)); Pagination<User> paga = userService.getList(pageNo, pageSize, keyword); content.append(JsonUtils.toJsonIncludeNull(paga)); } else if ("add".equals(method)) { String userName = request.getParameter("userName"); String password = request.getParameter("password"); String realName = request.getParameter("realName"); String mail = request.getParameter("mail"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); System.out.println(birthday); User user = new User(); user.setUserName(userName); user.setRealName(realName); user.setPassword(password); user.setGender(gender); user.setMail(mail); // user.setBirthday(birthday); userService.createUser(user); content.append("{\"result\":\"success\", \"msg\":\"success\"}"); } else if ("delete".equals(method)) { String id_str = request.getParameter("id"); int id = Integer.parseInt(id_str); userService.deleteUser(id); content.append("{\"result\":\"success\", \"msg\":\"success\"}"); } else if ("info".equals(method)) { String id_str = request.getParameter("id"); int id = Integer.parseInt(id_str); User user = userService.getUser(id); content.append(JsonUtils.toJson(user)); } else if ("update".equals(method)) { String id_str = request.getParameter("id"); String userName = request.getParameter("userName"); String password = request.getParameter("password"); String realName = request.getParameter("realName"); String mail = request.getParameter("mail"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); int id = Integer.parseInt(id_str); User user = new User(); user.setId(id); user.setUserName(userName); user.setRealName(realName); user.setPassword(password); user.setGender(gender); user.setMail(mail); // user.setBirthday(birthday); userService.updateUser(user); content.append("{\"result\":\"success\", \"msg\":\"success\"}"); } // response.setContentType("text/html"); // response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println(content); out.flush(); out.close();
2.flex端准备
(1)用lashbuilder 创建 flex工程 FlextTopTest
在创建过程中,选择application server时,选择java,具体配置如下
注意 :root folder是java web项目发布到tomcat中的文件目录
root url:一看就明了了
(2)具体编码实现,现把用户列表的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" minWidth="955" minHeight="600" applicationComplete="initApp()"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> <s:RemoteObject id="userService" destination="userService" fault="Alert.show(event.fault.faultString,'Error')"> </s:RemoteObject> </fx:Declarations> <fx:Script> <![CDATA[ import com.adobe.serialization.json.JSON; import com.ln.ydc.flex.commons.core.utils.*; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.controls.dataGridClasses.DataGridColumn; import mx.events.CloseEvent; import mx.events.ListEvent; import mx.formatters.DateFormatter; import mx.managers.PopUpManager; // 数据源 [Bindable] private var dataArray:ArrayCollection; // 分页数据 [Bindable] private var pageNo:uint=1; [Bindable] private var pageSize:uint=20; [Bindable] private var totalRecord:uint; [Bindable] private var totalPage:uint; // 公共数据 [Bindable] public static var genderArray:ArrayCollection=new ArrayCollection([{id: 0, label: '男'}, {id: 1, label: '女'}]); public function initApp():void { // 加个时间戳,解决缓存不更新问题 var params:URLVariables=new URLVariables("temp=" + Math.random()); params.pageNo=pageNo; params.pageSize=pageSize; var ru:RequestUtils=new RequestUtils; ru.doPostRequest(UrlConst.USER_LIST_URL, params, initDataSource); btn_add.addEventListener(MouseEvent.CLICK, popUserAddWin); btn_info.addEventListener(MouseEvent.CLICK, popUserInfoWin); btn_update.addEventListener(MouseEvent.CLICK, popUserUpdateWin); btn_delete.addEventListener(MouseEvent.CLICK, btn_deleteClick); btn_refesh.addEventListener(MouseEvent.CLICK, btn_refeshClick); } // 设置数据源 private function initDataSource(e:Event):void { var loader:URLLoader=URLLoader(e.target); var dataObj:Object=JSON.decode(loader.data) as Object; pageNo=dataObj["pageNo"]; pageSize=dataObj["pageSize"]; totalRecord=dataObj["totalRecord"]; totalPage=dataObj["totalPage"]; // var array:Array=JSON.decode(String(dataObj["records"])) as Array; dataArray=new ArrayCollection(dataObj["records"]); dg.dataProvider=dataArray; } // 弹出用户添加窗口事件 private function popUserAddWin(evt:MouseEvent):void { var childWin:UserAdd=new UserAdd(); childWin.owner=this; PopUpManager.addPopUp(childWin, this, true); PopUpManager.centerPopUp(childWin); } // 弹出用户信息窗口事件 private function popUserInfoWin(evt:MouseEvent):void { if (dg.selectedItem == null) { Alert.show("请先选择一个用户", "友情提示"); return; } var childWin:UserInfo=new UserInfo(); childWin.owner=this; childWin.setUserId(dg.selectedItem.id); PopUpManager.addPopUp(childWin, this, true); PopUpManager.centerPopUp(childWin); } // 弹出用户编辑窗口事件 private function popUserUpdateWin(evt:MouseEvent):void { if (dg.selectedItem == null) { Alert.show("请先选择一个用户", "友情提示"); return; } var childWin:UserUpdate=new UserUpdate(); childWin.owner=this; childWin.setUserId(dg.selectedItem.id); PopUpManager.addPopUp(childWin, this, true); PopUpManager.centerPopUp(childWin); } // 删除用户事件 private function btn_deleteClick(evt:MouseEvent):void { if (dg.selectedItem == null) { Alert.show("请先选择一个用户", "友情提示"); } else { var params:URLVariables=new URLVariables; params.id=dg.selectedItem.id; var ru:RequestUtils=new RequestUtils; ru.doPostRequest(UrlConst.USER_DELETE_URL, params, resultHandler); } } // 刷新列表事件 private function btn_refeshClick(evt:MouseEvent):void { var params:URLVariables=new URLVariables; params.temp=Math.random(); params.pageNo=pageNo; params.pageSize=pageSize; var ru:RequestUtils=new RequestUtils; ru.doPostRequest(UrlConst.USER_LIST_URL, params, initDataSource); } // 默认回调函数 private function resultHandler(evt:Event):void { var loader:URLLoader=URLLoader(evt.target); var data:Object=JSON.decode(String(loader.data)); Alert.show("操作" + data["result"] + "", "信息提示", Alert.YES | Alert.NO, this, alertClickHandler); } private function alertClickHandler(evt:CloseEvent):void { if (evt.detail == Alert.YES) { // status.text = "You answered Yes"; } else { // status.text = "You answered No"; } } private function toPage(pageNo:uint):void { var params:URLVariables=new URLVariables; params.temp=Math.random(); params.pageNo=pageNo; params.pageSize=pageSize; var ru:RequestUtils=new RequestUtils; ru.doPostRequest(UrlConst.USER_LIST_URL, params, initDataSource); } private function topPage():void { toPage(1); } private function prevPage():void { toPage(pageNo - 1); } private function nextPage():void { toPage(pageNo + 1); } private function endPage():void { toPage(totalPage); } // 生日格式化 日期 private function formatBirthday(item:Object, column:GridColumn):String { // trace("UserManager\t" + item.birthday + "\t" + DateUtils.formatDate(String(item.birthday))); // trace(DateUtils.formatDate(String(item.birthday) + "ddddd")); // return DateUtils.formatDate(String(item.birthday)); return item.birthday; } private function formatGender(item:Object, column:GridColumn):String { var gender:String="男"; if (item.gender.toString() == "1") { gender="女"; } return gender; } ]]> </fx:Script> <s:DataGrid id="dg" x="43" y="58" width="851" height="357" requestedRowCount="4"> <s:columns> <s:ArrayList> <s:GridColumn dataField="id" headerText="ID"> </s:GridColumn> <s:GridColumn dataField="userName" headerText="用户名"> </s:GridColumn> <s:GridColumn dataField="realName" headerText="姓名"> </s:GridColumn> <s:GridColumn dataField="gender" headerText="性别" labelFunction="formatGender"> </s:GridColumn> <s:GridColumn dataField="mail" headerText="邮箱"> </s:GridColumn> <s:GridColumn dataField="birthday" headerText="生日" labelFunction="formatBirthday"> </s:GridColumn> <s:GridColumn dataField="registerDate" headerText="注册日期"> </s:GridColumn> </s:ArrayList> </s:columns> </s:DataGrid> <s:Button id="btn_search" x="206" y="25" label="查询"/> <s:Button id="btn_add" x="303" y="25" label="增加"/> <s:Button id="btn_delete" x="401" y="25" label="删除"/> <s:Button id="btn_update" x="501" y="25" label="修改"/> <s:Button id="btn_info" x="587" y="25" label="查看"/> <s:Button id="btn_refesh" x="675" y="25" label="刷新"/> <s:TextInput id="input_keyword" x="43" y="24"/> <s:Label x="51" y="432" text="第 {pageNo}/{totalPage} 页 共 {totalRecord} 条数据"/> <s:Button id="btn_top" x="210" y="423" label="首页" buttonDown="topPage()"/> <s:Button id="btn_prev" x="307" y="423" label="上一页" buttonDown="prevPage()"/> <s:Button id="btn_next" x="405" y="423" label="下一页" buttonDown="nextPage()"/> <s:Button id="btn_end" x="505" y="423" label="尾页" buttonDown="endPage()"/> </s:Application>
其它具体实现见附件
3.数据库准备
表结构
DROP TABLE IF EXISTS `t_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `realName` varchar(25) DEFAULT NULL, `userName` varchar(25) DEFAULT NULL, `pwd` varchar(50) DEFAULT NULL, `birthday` date DEFAULT NULL, `gender` varchar(1) DEFAULT NULL, `mail` varchar(50) DEFAULT NULL, `registerDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `deleteFlag` int(1) DEFAULT '0', `lastModifyDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `userName` (`userName`), UNIQUE KEY `mail` (`mail`) ) ENGINE=InnoDB AUTO_INCREMENT=156 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */;
----------------------------
遇到的一些问题:
1.乱码 java端使用过虑器解决
2.flex 弹出窗口
----------------------------
不足及未实现:
1.java日期与flex格式化未解决
2.未数据验证
----------------------------
参考: