Flex 工具类
package Util { import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class RequestUtil { public function RequestUtil() { } public function doPostRequest(url:String, params:URLVariables, callback:Function):void { var request:URLRequest=new URLRequest(); request.url=url; request.method=URLRequestMethod.POST; request.data=params; var loader:URLLoader=new URLLoader(); loader.load(request); loader.addEventListener(Event.COMPLETE, callback); } // 默认回调函数 /* public function resultHandler(evt:Event):void { var loader:URLLoader=URLLoader(evt.target); var name:String=loader.data as String; }*/ } }
Flex 主代码
<?xml version="1.0" encoding="utf-8"?> <s:Module 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="800" height="400" creationComplete="module_creationCompleteHandler(event)"> <fx:Style source="assets/myCss.css"/> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <fx:Script> <![CDATA[ import EO.EmpEO; import Util.BaseUtil; import Util.RainHttp; import Util.RequestUtil; import Util.UrlConst; import com.adobe.serialization.json.JSON; import com.adobe.serialization.json.JSONDecoder; import component.AddEmp; import component.EmpDetail; import mx.collections.ArrayCollection; import mx.collections.XMLListCollection; import mx.controls.Alert; import mx.controls.DateField; import mx.events.FlexEvent; import mx.managers.PopUpManager; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import spark.events.GridSelectionEvent; import spark.events.IndexChangeEvent; //查询动作的时候标示是哪种查询 type:all,dept,position,fuzzy ;data:all,deptNo,positionNo,fuzzyInput; private var reqSelectBy:Object=null; [Bindable]//emp 数据 private var empList:ArrayCollection; [Bindable]//dept 数据 private var deptList:ArrayCollection; [Bindable]//position 数据 private var positionList:ArrayCollection; [Bindable]//每页数据条数 private var pageSIZE:Number=10; [Bindable]//当前页号 private var pageNo:Number=1; [Bindable]//共页数 private var totalPage:Number=0; [Bindable]//总记录数 private var totalRecord:Number=0; //模块初始向服务器请求数据 protected function module_creationCompleteHandler(event:FlexEvent):void { this.reqSelectBy=new Object(); this.reqSelectBy.type=UrlConst.reqSelectByAll; this.reqSelectBy.data="all"; sendHttpRequest(UrlConst.EMP_SELECTBY_URL,this.pageNo,this.pageSIZE,this.reqSelectBy); } //双击DataGrid 将选择的item转换为EmpEO对象,弹出详细列表 protected function empDataGrid_doubleClickHandler(event:MouseEvent):void { if(empDataGrid.selectedItem==null){ Alert.show("请先选择一个用户", "友情提示"); return; } var empDetail:EmpDetail=new EmpDetail(); PopUpManager.addPopUp(empDetail,this,true); PopUpManager.centerPopUp(empDetail); //将empDataGrid选择的item转换为EmpEO 传递进弹出框 empDetail.emp=BaseUtil.coverItemToEmp(empDataGrid.selectedItem); } //分页按钮响应函数 protected function paginationBt_clickHandler(event:MouseEvent):void { switch(event.target.id.charAt(0)) { case 'l': {//最后一页 sendHttpRequest(UrlConst.EMP_SELECTBY_URL,this.totalPage,this.pageSIZE,this.reqSelectBy); break; } case 'n': {//下一页 sendHttpRequest(UrlConst.EMP_SELECTBY_URL,this.pageNo+1,this.pageSIZE,this.reqSelectBy); break; } case 'p': {//前一页 sendHttpRequest(UrlConst.EMP_SELECTBY_URL,this.pageNo-1,this.pageSIZE,this.reqSelectBy); break; } case 'f': {//第一页 sendHttpRequest(UrlConst.EMP_SELECTBY_URL,1,this.pageSIZE,this.reqSelectBy); break; } } } //向服务器请求数据 url,当前页,每页记录数,根据什么参数查询数据 private function sendHttpRequest(url:String,pageNo:Number,pageSIZE:Number,selectBy:Object):void{ //要传递的参数 var object:Object=new Object(); object.pageNo=pageNo;//第几页 object.pageSize=pageSIZE;//每页记录数 object.selectBy=selectBy;//查询条件 //参数转化为json后赋值给URLVariables var params:URLVariables=new URLVariables(); params.requestData=JSON.encode(object); //将地址,参数,处理函数传递给RequestUtil工具类 var requestUtil:RequestUtil=new RequestUtil; requestUtil.doPostRequest(url, params, requestResult); } //回调函数sendHttpRequest private function requestResult(event:Event):void{ var loader:URLLoader = URLLoader(event.target); var object:Object=JSON.decode(loader.data) as Object; this.totalPage=object["totalPage"]; this.totalRecord=object["totalRecord"]; this.pageNo=object["pageNo"]; this.empList=new ArrayCollection(object["empList"]); //雇员信息 this.deptList=new ArrayCollection(object["deptList"]);//部门 this.positionList=new ArrayCollection(object["positionList"]);//职位 } //部门下拉框change事件:1.向服务器发送信息获取对应部门的员工信息 2.刷新 职位列表的数据源 使得职位符合对应的部门 protected function deptDDL_changeHandler(event:IndexChangeEvent):void { this.reqSelectBy=new Object(); this.reqSelectBy.type=UrlConst.reqSelectByDept; this.reqSelectBy.data=String(deptDDL.selectedItem.dept_no); sendHttpRequest(UrlConst.EMP_SELECTBY_URL,1,this.pageSIZE,this.reqSelectBy); } //职位下拉框change事件:1.向服务器发送信息获取对应职位的员工信息 protected function positionDDL_changeHandler(event:IndexChangeEvent):void { this.reqSelectBy=new Object(); this.reqSelectBy.type=UrlConst.reqSelectByPosition; this.reqSelectBy.data=String(positionDDL.selectedItem.position_id); sendHttpRequest(UrlConst.EMP_SELECTBY_URL,1,this.pageSIZE,this.reqSelectBy); } protected function fuzzyBtn_clickHandler(event:MouseEvent):void { this.reqSelectBy=new Object(); this.reqSelectBy.type=UrlConst.reqSelectByfuzzy; this.reqSelectBy.data=fuzzyInput.text; sendHttpRequest(UrlConst.EMP_SELECTBY_URL,1,this.pageSIZE,this.reqSelectBy); } protected function addBtn_clickHandler(event:MouseEvent):void { var addEmp:AddEmp=new AddEmp(); addEmp.owner=this; PopUpManager.addPopUp(addEmp,this,true); PopUpManager.centerPopUp(addEmp); } ]]> </fx:Script> <s:Button id="addBtn" x="50" y="10" label="添加" click="addBtn_clickHandler(event)"/> <s:Button id="deleteBtn" x="120" y="10" label="删除"/> <s:Button id="updateBtn" x="190" y="10" label="修改"/> <s:Button id="fuzzyBtn" x="686" y="10" label="查询" click="fuzzyBtn_clickHandler(event)"/> <s:TextInput id="fuzzyInput" x="560" y="10" toolTip="对姓名,身份证,员工号进行模糊查询"/> <!--requireSelection="true" 默认选择第一项--> <s:DropDownList id="deptDDL" x="280" y="10" prompt="选择部门" labelField="dept_name" dataProvider="{this.deptList}" change="deptDDL_changeHandler(event)"/> <s:DropDownList id="positionDDL" x="400" y="10" prompt="选择职位" labelField="position_name" dataProvider="{this.positionList}" change="positionDDL_changeHandler(event)"/> <s:Button x="570" bottom="10" label="详细" click="empDataGrid_doubleClickHandler(event)"/> <s:Button id="lastBt" x="260" bottom="10" label="尾页" click="paginationBt_clickHandler(event)"/> <s:Button id="nextBt" x="190" bottom="10" label="下一页" click="paginationBt_clickHandler(event)"/> <s:Button id="preBt" x="120" bottom="10" label="上一页" click="paginationBt_clickHandler(event)"/> <s:Button id="firstBt" x="50" bottom="10" label="首页" click="paginationBt_clickHandler(event)"/> <s:Label x="371" y="368" text="共{this.pageNo}/{this.totalPage}页"/> <s:DataGrid id="empDataGrid" top="50" width="700" height="300" dataProvider="{empList}" doubleClick="empDataGrid_doubleClickHandler(event)" doubleClickEnabled="true" > <s:columns> <s:ArrayList> <s:GridColumn dataField="emp_no" headerText="员工号"></s:GridColumn> <s:GridColumn dataField="emp_id" headerText="身份证号"></s:GridColumn> <s:GridColumn dataField="emp_name" headerText="名称"></s:GridColumn> <s:GridColumn dataField="emp_sex" headerText="性别"></s:GridColumn> <s:GridColumn dataField="dept_name" headerText="部门"></s:GridColumn> <s:GridColumn dataField="position_name" headerText="职位"></s:GridColumn> </s:ArrayList> </s:columns> </s:DataGrid> </s:Module>
Servlet 代码
package com.hr.co; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import com.hr.modal.bean.DeptEO; import com.hr.modal.bean.PositionEO; import com.hr.modal.bean.EmpEO; import com.hr.modal.dao.IEmpDao; import com.hr.modal.dao.impl.EmpDao; public class EmpCO extends HttpServlet { //数据库操作 IEmpDao idao = null; //请求的参数数据 Object requestData=null; public EmpCO() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到请求的操作 String method = request.getParameter("method"); System.out.println("Flex method:"+method); //得到请求的参数数据 requestData = request.getParameter("requestData"); //响应的数据 JSONObject respJson=null; PrintWriter out = response.getWriter(); switch (method.charAt(0)) { case 'a':// Add break; case 'd':// Delete deleteEmp(response); break; case 'u':// Update break; case 's':// SelectBy if (requestData != null) { respJson=selectBy(); }else { System.out.println("没收到参数"); } break; default: break; } //响应返回数据 out.print(respJson); out.flush(); out.close(); } public void init() throws ServletException { idao = new EmpDao(); } public JSONObject selectBy() { try { // 解析请求参数 JSONObject jsonObject = new JSONObject(requestData.toString()); int pageNo = jsonObject.getInt("pageNo");// 第几页 int pageSize = jsonObject.getInt("pageSize");// 每页记录数 JSONObject selectBy = jsonObject.getJSONObject("selectBy");// 查询的条件 String type=selectBy.getString("type"); String data=String.valueOf(selectBy.getString("data")); // 响应请求=========================== JSONObject respJson =null; // 要查询的总记录数 int totalRecord=0; // 总页数 int totalPage =0; // 查询数据 ArrayList<EmpEO> empList =null; ArrayList<PositionEO> positionList = null; ArrayList<DeptEO> deptList = idao.readDept(); //全部查询========================================= if("all".equals(type)){ totalRecord = idao.getEmpCount(); totalPage = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize) + 1; // 分析请求的页数是否合法 pageNo = (pageNo >= totalPage) ? (totalPage) : (pageNo); pageNo = (pageNo <= 1) ? (1) : (pageNo); empList = idao.readEmps((pageNo - 1)* pageSize, pageSize); positionList = idao.readPosition(); //根据部门查询========================================= }else if("dept".equals(type)){ int deptNo=Integer.parseInt(data); totalRecord = idao.getEmpCountByDept(deptNo); totalPage = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize) + 1; // 分析请求的页数是否合法 pageNo = (pageNo >= totalPage) ? (totalPage) : (pageNo); pageNo = (pageNo <= 1) ? (1) : (pageNo); empList = idao.getEmpByDept(deptNo,(pageNo - 1)* pageSize, pageSize); positionList = idao.getPositionByDept(deptNo); } //根据职位查询========================================= else if("position".equals(type)){ int positionId=Integer.parseInt(data); totalRecord = idao.getEmpCountByPosition(positionId); totalPage = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize) + 1; // 分析请求的页数是否合法 pageNo = (pageNo >= totalPage) ? (totalPage) : (pageNo); pageNo = (pageNo <= 1) ? (1) : (pageNo); empList = idao.getEmpByPosition(positionId,(pageNo - 1)* pageSize, pageSize); positionList = idao.readPosition(); } //模糊查询========================================= else if("fuzzy".equals(type)){ totalRecord = idao.getEmpCountByFuzzy(data); totalPage = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize) + 1; // 分析请求的页数是否合法 pageNo = (pageNo >= totalPage) ? (totalPage) : (pageNo); pageNo = (pageNo <= 1) ? (1) : (pageNo); empList = idao.getEmpByFuzzy(data,(pageNo - 1)* pageSize, pageSize); positionList = idao.readPosition(); } //组装返回的数据包================================ respJson = new JSONObject(); respJson.put("pageNo", pageNo);// 第几页 respJson.put("totalRecord", totalRecord);// 总记录数 respJson.put("totalPage", totalPage);// 总页数 respJson.put("empList", empList);// 查询结果 respJson.put("positionList", positionList); respJson.put("deptList", deptList); return respJson; } catch (JSONException e) { e.printStackTrace(); } return null; } public void deleteEmp(HttpServletResponse response){ if (requestData != null) { try { JSONObject jsonObject = new JSONObject(requestData.toString()); int empNo = jsonObject.getInt("emp_no"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }