如何從服務(wù)器端獲得數(shù)據(jù)并通過Flex以圖表形式展現(xiàn)出來,主要思路是:用戶通過瀏覽器調(diào)用嵌入Flex應(yīng)用的html頁面->Flex應(yīng)用發(fā)送請求到服務(wù)端請求數(shù)據(jù)->服務(wù)端將數(shù)據(jù)返回給Flex應(yīng)用->Flex向用戶展示數(shù)據(jù)。 下面分別從服務(wù)端和Flex進行說明:
1.編寫服務(wù)端
服務(wù)端用來向Flex應(yīng)用返回請求的數(shù)據(jù)。這里的數(shù)據(jù)格式設(shè)置為XML數(shù)據(jù)。對于XML數(shù)據(jù),可以直接返回一個XML文件或者通過編碼返回XML格式的數(shù)據(jù)。這里我們采用后者,這里的服務(wù)端還接收一個參數(shù):type,根據(jù)type不同返回不同的XML數(shù)據(jù)。
- package service;
-
- import java.io.*;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
-
-
-
-
-
- public class DataServiceServlet extends HttpServlet {
-
-
-
-
-
-
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/xml;charset=UTF-8");
- PrintWriter out = response.getWriter();
- try {
-
- String type = request.getParameter("type");
-
- StringBuilder xml = new StringBuilder();
- xml.append("<?xml version='1.0' encoding='UTF-8'?>");
- if ("1".equals(type)) {
- xml.append("<root>");
- xml.append("<Expense name='Taxses' value='3000'/>");
- xml.append("<Expense name='Rent' value='1520'/>");
- xml.append("<Expense name='Bills' value='500'/>");
- xml.append("</root>");
- } else if ("2".equals(type)) {
- xml.append("<root>");
- xml.append("<Expense name='Taxses' value='5000'/>");
- xml.append("<Expense name='Rent' value='1020'/>");
- xml.append("<Expense name='Bills' value='210'/>");
- xml.append("</root>");
- }
- out.println(xml.toString());
- } finally {
- out.close();
- }
- }
-
-
-
-
-
-
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
-
-
-
-
-
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
-
-
-
-
- public String getServletInfo() {
- return "Short description";
- }
-
- }
服務(wù)端很簡單,就是返回請求數(shù)據(jù)。
2.編寫Flex應(yīng)用
這個例子總Flex需要向服務(wù)端發(fā)送請求的同時,傳遞一個參數(shù)。用Flex發(fā)送帶參數(shù)請求很簡單,但是如何向Flex應(yīng)用傳遞參數(shù),卻有些繁瑣。下面先來看Flex應(yīng)用如何獲得外部傳來的參數(shù):
- <?xml version="1.0"?>
-
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- initialize="getParams();"> //<STRONG style="BACKGROUND-COLOR: #ffff66; COLOR: black">Flex</STRONG>應(yīng)用初始化時,向服務(wù)端獲取數(shù)據(jù)
- <mx:Script><![CDATA[
- import mx.collections.ArrayCollection;
- import mx.rpc.http.HTTPService;
- import mx.controls.Alert;
-
- [Bindable]
- private var service:HTTPService ;
-
- private function get_Label(item:Object, field:String, index:Number, percentValue:Number):String
- {
- return item["name"].toString()+":"+item[field].toString();
- }
-
- //獲得參數(shù)
- private function getParams():void {
- //獲得參數(shù)
- var params:Object = this.parameters;
- if (params != null) {
- //向服務(wù)端請求數(shù)據(jù)
- service = DataLoader.getData(params["type"].toString());
- } else {
- Alert.show("No params");
- }
-
- }
-
-
- ]]></mx:Script>
-
- <mx:Panel title="Pie Chart" backgroundColor="#FFFFFF">
- //展示餅狀圖
- <mx:PieChart id="myChart"
- dataProvider="{service.lastResult.root.Expense}" //獲得服務(wù)端返回的數(shù)據(jù)
- showDataTips="true"
- >
- <mx:series>
- <mx:PieSeries
- field="value"
- nameField="name"
- labelPosition="callout"
- labelFunction="get_Label"
- />
- </mx:series>
- </mx:PieChart>
- <mx:Legend dataProvider="{myChart}"/>
- </mx:Panel>
- </mx:Application>
從上面的代碼可以看出,Flex獲得參數(shù)的方法:
- private function getParams():void {
-
- <SPAN style="COLOR: #ff0000">var params:Object = this.parameters;</SPAN>
-
-
- if (params != null) {
-
- service = DataLoader.getData(<SPAN style="COLOR: #ff0000">params["type"].toString()</SPAN>
-
- );
- } else {
- Alert.show("No params");
- }
-
- }
在應(yīng)用加載的時候,通過調(diào)用getParams()方法,獲得傳入的參數(shù),并向服務(wù)端請求數(shù)據(jù)。
Flex向服務(wù)端請求數(shù)據(jù)有3種方式:REST-sytle service,web service,Remote object service。這里使用的是第一種方式。REST-style service實際上就是采用HTTP協(xié)議通信的方式。Flex提供了HTTPService component,使用起來很方便。這里用的是ActionScript:
DataLoader.as
- package
- {
- import mx.controls.Alert;
- import mx.rpc.events.FaultEvent;
- import mx.rpc.events.ResultEvent;
- import mx.rpc.http.HTTPService;
-
- public class DataLoader
- {
-
- public function DataLoader()
- {
- }
- public static function getData(type:Object):HTTPService {
- var service:HTTPService;
- service = new HTTPService();
- service.url = "http://localhost:7001/DataService/getData?type="+type;
- service.method = "POST";
- service.addEventListener("result", httpResult);
- service.addEventListener("fault", httpFault);
- service.send();
-
- return service;
- }
-
- public static function httpResult(event:ResultEvent):void {
- var result:Object = event.result;
- }
-
- public static function httpFault(event:FaultEvent):void {
- var faultstring:String = event.fault.faultString;
- Alert.show("Fault: " + faultstring);
- }
- }
下面的代碼得到服務(wù)端返回的數(shù)據(jù):
- <mx:PieChart id="myChart"
- dataProvider="<SPAN style="COLOR: #ff0000">{service.lastResult.root.Expense}</SPAN>
-
- " //獲得服務(wù)端返回的數(shù)據(jù)
- showDataTips="true"
- >
- 。。。
- </mx:PieChart>
之后,Flex就可以根據(jù)獲得的數(shù)據(jù)將圖展現(xiàn)出來了。
上面說了Flex如何獲得參數(shù)并向服務(wù)端發(fā)送請求,那么參數(shù)是如何傳遞給Flex應(yīng)用的呢?這里就有點復(fù)雜了。需要寫一段JS腳本進行參數(shù)的傳遞。
chartType.js
- var requiredMajorVersion = 9;
- var requiredMinorVersion = 0;
- var requiredRevision = 0;
-
- <!-- 動態(tài)創(chuàng)建Flash -->
- <!-- id:應(yīng)用編號 -->
- <!-- url:嵌入網(wǎng)頁的SWF文件名稱 -->
- <!-- width:應(yīng)用在網(wǎng)頁中的寬度 -->
- <!-- high:應(yīng)用在網(wǎng)頁中的高度 -->
- <!-- type:服務(wù)端需要的參數(shù) -->
-
- function sendParameters(id, url, width, high, type)
- {
- var hasProductInstall = DetectFlashVer(6, 0, 65);
- var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
-
- if(hasProductInstall && !hasRequestedVersion)
- {
- var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
- var MMredirectURL = window.location;
- document.title = document.title.slice(0, 47) + " - Flash Player Installation";
- var MMdoctitle = document.title;
-
- <SPAN style="COLOR: #ff0000">AC_FL_RunContent</SPAN>
-
- (
- "id", id,
- "src", "playerProductInstall",
- "name", url,
- "width", width,
- "height", high,
- "menu", false,
- "wmode", "opaque",
- "align", "middle",
- "quality", "high",
- "bgcolor", "#808080",
- "allowScriptAccess","always",
- "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
- "type", "application/x-shockwave-flash",
- "pluginspage", "http://www.adobe.com/go/getflashplayer");
- }
- else if(hasRequestedVersion)
- {
- var flashvars = "type=" + type;
-
- <SPAN style="COLOR: #ff0000">AC_FL_RunContent</SPAN>
-
- (
- "id", id,
- "src", url,
- "name", url,
- "flashvars", flashvars,
- "menu", false,
- "width", width,
- "height", high,
- "wmode", "opaque",
- "align", "middle",
- "quality", "high",
- "bgcolor", "#808080",
- "allowScriptAccess","always",
- "type", "application/x-shockwave-flash",
- "pluginspage", "http://www.adobe.com/go/getflashplayer");
- }
- else
- {
- var alternateContent = 'Alternate HTML content should be placed here. '
- + 'This content requires the Adobe Flash Player. '
- + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
- document.write(alternateContent);
- }
- }
-
- function getInfoForFlash(type)
- {
- if(type.toLowerCase().indexOf("f_code") != -1)
- {
- var target = document.getElementById("f_code");
- if(target != null)
- return target.value;
- else
- return "g01";
- }
- else if(type.toLowerCase().indexOf("f_title") != -1)
- {
- var target = document.getElementById("f_title");
- if(target != null)
- return target.value;
- else
- return "unkown";
- }
- else
- return "unkown";
- }
上面的腳本中,調(diào)用了AC_FL_RunContent方法,這個方法是Flex提供給我們的一個方法,用FlexBuilder創(chuàng)建一個Flex Project后,就可以在html-template這個文件夾中看到一個叫AC_OETags.js的文件。這個方法就在這個文件中。下面是調(diào)用Flex應(yīng)用的html頁面:
chart.html
- <html lang="en">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title></title>
- <script src="AC_OETags.js" language="javascript"></script>
-
- </head>
- <body bgcolor="#EBEAE5" leftmargin="0" topmargin="0">
- <script language="JavaScript" type="text/javascript" src="history.js"></script>
- <script language="javascript" type="text/javascript" src="chartType.js"></script>
- <table width="770" border="0" cellspacing="0" cellpadding="0" align="center">
- <tr>
- <td></td>
- </tr>
- <tr>
- <td align="center">
- <script>
- sendParameters("Chart1", "Chart1", 800, 600, "2");
- </script>
- </td>
- </tr>
- </table>
- </body>
- </html>
這個HTML頁面包含了AC_OETags.js和chartType.js。通過sendParameters方法向Flex應(yīng)用傳遞參數(shù),并將應(yīng)用嵌入網(wǎng)頁中顯示出來。
|