轉載地址;http://yghjoe.iteye.com/blog/1035659
當使用fusionchart時,可能會寫一些很多的xml文件,有時候很麻煩。但是完全可以自己封裝起來。根據自己的意願,得出想要的封裝。
我這裏簡單的封裝了一下,只是說說大概的使用方法。
首先在後臺代碼中自己寫一個工具類,這個類就是對fusionchart的簡單封裝。只提供方法供外邊使用者向裏面提供數據,就可以生成fusionchart的所有xml格式的內容。返回的結果是符合xml格式的字符串。這樣得出的數據當做參數傳到前臺頁面,前臺頁面接受這個變量,放到指定的位置就可以顯示出來fusionchart的圖形。
我這裏只提供大概的思路,你們可以結合自己的想法去寫。也提供了代碼下載,我主要把核心的代碼給提供下載了。
package com.joe.tool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
/**
* 畫圖工具,主要用來畫二維和三維圖形(餅狀圖,柱狀圖,曲線圖)
* 使用說明:
* 1, 創建該類的一個構造函數,如果構造函數裏的參數不是你想要的,你可以通過get/set方法設置.
* 2, 根據自己的需要畫什麼樣的圖就調用什麼方法。
* 3, 例子: DrawDesigns d = new DrawDesigns(......); String str = d.drawPie2D();
* 這個str參數就是全部數據,前臺可以直接使用這個參數(str),注意頁面不用導入js文件。
* 前臺頁面:(比如jsp頁面) ${str} 或者 <%=str%>
*
* @author joe
*
*/
public class DrawDesigns {
// default params
private static final String CAPTION = "統計分析圖";
private static final String XAXISNAME = "數據源名稱";
private static final String YAXISNAME = "Value";
private static final Integer WIDTH = 600;// 默認的寬度,意思同width變量一樣
private static final Integer HEIGHT = 400;// 默認的高度,意思同height變量一樣
private static final String JSPATH = "FusionChartsFree/JSClass/FusionCharts.js";
private static final String SWFPATH = "FusionChartsFree/Charts/";
// private static final String XMLHEADER = "<?xml version=\"1.0\"
// encoding=\"UTF-8\"?>";
// user-defind
private String caption;// 圖形的標題名稱
private String xAxisName;// 橫向座標軸(x軸)名稱
private String yAxisName;// 縱向座標軸(y軸)名稱
private Integer width;// x軸寬,其實設置成Double類型的變量也可以,但是沒有必要精算到浮點型,Integer就夠了,除非業務有必要的說明
private Integer height;// y軸寬,其實設置成Double類型的變量也可以,但是沒有必要精算到浮點型,Integer就夠了,除非業務有必要的說明
private String jsPath;// 這種寫法意思是FusionCharts這個包和你自己寫的文件包處於同一個目錄下,默認的js路徑就是這個
private String swfPath;// 這個只能指定包名,因爲這個Charts包下面全是swf文件,只能根據客戶需求加swf文件
private String divId = "drawDiv" + UUID.randomUUID().toString();// 把封裝好的xml數據放到前臺頁面顯示在哪個區域,比如div,所以areaName意思是指定這個區域的名字,這裏給他一個默認的。
private String colors[] = { "1D8BD1", "F1683C", "2AD62A", "DBDC25",
"649665", "4169E1", "087eb6", "BA55D3", "D2691E", "FF7F50",
"32CD32", "4682B4" };// 指定顏色,可以根據自己的喜歡隨便寫,這個數組的長度不限,主要是顯示圖形時好區分,如果你弄成統一的顏色,會很單調,可以考慮編寫個隨機顏色程序。
private String myChartName;
// 一維數據(意思是比如曲線圖上只顯示一條曲線)
private List<Map<Object, Object>> oneDimensionsList = new ArrayList<Map<Object, Object>>();
// 多維數據(意思是比如曲線圖上顯示多條曲線)
private Map<Object, Map<Object, Object>> manyDimensionsMap = new HashMap<Object, Map<Object, Object>>();
// x軸名稱集合(是用來做多條曲線用的,主要是多個集合共享x軸名稱)
private List<String> xAxisNameList = new ArrayList<String>();
private boolean benchmark = false;//是否顯示基準線
private String benchmarkName;//基準線名稱
private Object benchmarkValue;//基準線值
/**
* 默認的構造方法
*/
public DrawDesigns() {
this.verifyParams();
}
/**
* 針對一維數據所建立的構造方法
* @param caption
* @param xAxisName
* @param yAxisName
* @param width
* @param height
* @param oneDimensionsList
*/
public DrawDesigns(String caption, String xAxisName, String yAxisName,
Integer width, Integer height, List<Map<Object, Object>> oneDimensionsList) {
this.caption = caption;
this.xAxisName = xAxisName;
this.yAxisName = yAxisName;
this.width = width;
this.height = height;
this.oneDimensionsList = oneDimensionsList;
this.verifyParams();
}
/**
* 針對一維數據所建立的構造方法,該方法含有js路徑
* @param caption
* @param xAxisName
* @param yAxisName
* @param width
* @param height
* @param jsPath
* @param swfPath
* @param oneDimensionsList
*/
public DrawDesigns(String caption, String xAxisName, String yAxisName,
Integer width, Integer height, String jsPath, String swfPath,
List<Map<Object, Object>> oneDimensionsList) {
this.caption = caption;
this.xAxisName = xAxisName;
this.yAxisName = yAxisName;
this.width = width;
this.height = height;
this.jsPath = jsPath;
this.swfPath = swfPath;
this.oneDimensionsList = oneDimensionsList;
this.verifyParams();
}
/**
* 該構造方法是爲多維數據寫的:
* List<String>含義是x軸的名稱,
* Map<Object, Map<Object, Object>>含義是每一維所對應的值的集合.
* 例子:List<String> = {"一月","二月","三月","四月","五月"}
* Map<Map<Object, Map<Object, Object>>>
* = {
* {2009年,{{"一月",100},{"二月",200},{"三月",300}...}},
* {2010年,{{"一月",100},{"二月",200},{"三月",300}...}}...
* }
* @param caption
* @param xAxisName
* @param yAxisName
* @param width
* @param height
* @param jsPath
* @param swfPath
* @param xAxisNameList
* @param manyDimensionsMap
*/
public DrawDesigns(String caption, String xAxisName, String yAxisName,
Integer width, Integer height, String jsPath, String swfPath,
List<String> xAxisNameList,
Map<Object, Map<Object, Object>> manyDimensionsMap) {
this.caption = caption;
this.xAxisName = xAxisName;
this.yAxisName = yAxisName;
this.width = width;
this.height = height;
this.jsPath = jsPath;
this.swfPath = swfPath;
this.xAxisNameList = xAxisNameList;
this.manyDimensionsMap = manyDimensionsMap;
}
/**
* 針對多維數據所建立的構造方法
* 同上一樣,只不過是不帶js路徑
* @param caption
* @param xAxisName
* @param yAxisName
* @param width
* @param height
* @param xAxisNameList
* @param manyDimensionsMap
*/
public DrawDesigns(String caption, String xAxisName, String yAxisName,
Integer width, Integer height, List<String> xAxisNameList,
Map<Object, Map<Object, Object>> manyDimensionsMap) {
this.caption = caption;
this.xAxisName = xAxisName;
this.yAxisName = yAxisName;
this.width = width;
this.height = height;
this.xAxisNameList = xAxisNameList;
this.manyDimensionsMap = manyDimensionsMap;
}
/**
* 獲取swf動畫的路徑
*
* @param swfName
* @return
*/
private String getSWFPath(String swfName) {
return this.swfPath + swfName;
}
/**
* 客戶有可能需要達標線,所以這裏設置一下達標線的參數
*
* @param ifBenchmark
* 是否顯示達標線
* @param benchmarkName
* 達標線名稱
* @param benchmarkValue
* 達標線值
*/
public void setBenchmark(boolean ifBenchmark, String benchmarkName,
Object benchmarkValue) {
this.benchmark = ifBenchmark;
this.benchmarkName = benchmarkName;
this.benchmarkValue = benchmarkValue;
}
/**
* 如果用戶在前臺不設置參數,例如這個參數爲null或者是"",那麼這裏給他一個默認的參數值
*/
private void verifyParams() {
if (this.width == null || this.width <= 0) {
this.width = WIDTH;
}
if (this.height == null || this.height <= 0) {
this.height = HEIGHT;
}
if (this.xAxisName == null || this.xAxisName.equals("")) {
this.xAxisName = XAXISNAME;
}
if (this.yAxisName == null || this.yAxisName.equals("")) {
this.yAxisName = YAXISNAME;
}
if (this.caption == null || this.caption.equals("")) {
this.caption = CAPTION;
}
if (this.jsPath == null || this.jsPath.equals("")) {
this.jsPath = JSPATH;
}
if (this.swfPath == null || this.swfPath.equals("")) {
this.swfPath = SWFPATH;
}
if (this.myChartName == null || this.myChartName.equals("")) {
this.myChartName = "myChart" + (new Random()).nextInt(10000);
}
if (this.oneDimensionsList.isEmpty()) {
this.oneDimensionsList = new ArrayList<Map<Object,Object>>();
}
if (this.manyDimensionsMap.isEmpty()) {
this.manyDimensionsMap = new HashMap<Object, Map<Object,Object>>();
}
if(this.xAxisNameList.isEmpty()) {
this.xAxisNameList = new ArrayList<String>();
}
// 以下代碼(三個for循環)是做測試用的
/* for (int i = 0; i < 10; i++) {
int value = (new Random()).nextInt(100);
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("x", "你好" + i);
map.put("y", value);
this.oneDimensionsList.add(map);
}
for (int i = 1; i <= 12; i++) {
this.xAxisNameList.add(i + "");
}
for (int i = 0; i < 3; i++) {
Map<Object, Object> m = new HashMap<Object, Object>();
for (int j = 1; j <= this.xAxisNameList.size(); j++) {
m.put(this.xAxisNameList.get(j - 1), (new Random())
.nextInt(100));
}
this.manyDimensionsMap.put("201" + i, m);
}
*/
}
/**
* 加載js
*
* @return
*/
private String getDivAndJs() {
return "<div style=\"width: 0px; height: 0px\"><script type=\"text/javascript\" src=\""
+ this.jsPath
+ "\"></script></div>"
+ "<div id=\""
+ this.divId + "\" align = \"center\">Fusion Chart.</div>";
}
/**
* 解析一維圖形的xml數據
*
* @return
*/
private String getOneDimensionsXmlData() {
StringBuffer buffer = new StringBuffer("");
buffer
.append("<chart caption='")
.append(this.caption)
.append("' xAxisName='")
.append(this.xAxisName)
.append("' yAxisName='")
.append(this.yAxisName)
.append(
"' showNames='1' decimalPrecision='0' baseFontSize='12' formatNumberScale='0' >");
for (Map<Object, Object> map : this.oneDimensionsList) {
buffer.append("<set label='").append(map.get("x")).append(
"' value='").append(map.get("y")).append("' color='")
.append(this.getRandomColor()).append("' />");
}
buffer.append("</chart>");
return buffer.toString();
}
/**
* 畫圖,主要是把js,xml,swf等數據封裝起來
*
* @param swfName
* @param xmlData
* @return
*/
private String getDrawChart(String swfName, String xmlData) {
StringBuffer buffer = new StringBuffer(this.getDivAndJs()
+ "<script type=\"text/javascript\"> ");
buffer.append("var ").append(this.myChartName).append(
"= new FusionCharts(\"" + this.getSWFPath(swfName)
+ "\", \"myChart" + UUID.randomUUID().toString()
+ "\", \"" + this.width + "\", \"" + this.height
+ "\", \"0\", \"0\"); ").append(this.myChartName)
.append(".setDataXML(\"" + xmlData + "\"); ").append(
this.myChartName).append(".render(\"").append(
this.divId).append("\");</script>");
return buffer.toString();
}
/**
* 解析多維圖形的xml數據
*
* @return
*/
private String getManyDimensionsXmlData() {
StringBuffer buffer = new StringBuffer("");
buffer
.append("<chart caption='")
.append(this.caption)
.append("' xAxisName='")
.append(this.xAxisName)
.append("' yAxisName='")
.append(this.yAxisName)
.append(
"' showValues='0' baseFontSize='12' palette='1' showFCMenuItem='1' imageSave='1'>");
buffer.append("<categories>");
for (String str : xAxisNameList) {
buffer.append("<category label='" + str + "' />");
}
buffer.append("</categories>");
for (Map.Entry<Object, Map<Object, Object>> values : this.manyDimensionsMap.entrySet()) {
buffer.append("<dataset seriesName='").append(values.getKey()).append("'>");
for (String str : this.xAxisNameList) {
buffer.append("<set value='").append(values.getValue().get(str)).append("'/>");
}
buffer.append("</dataset>");
}
buffer.append(this.benchmark());
buffer.append("</chart>");
return buffer.toString();
}
/**
* 封裝達標線的xml數據
* @return
*/
private String benchmark() {
StringBuffer buffer = new StringBuffer("");
if (this.benchmark
&& (this.benchmarkName != null && !this.benchmarkName
.equals(""))
&& (this.benchmarkValue != null && !this.benchmarkValue
.equals(""))) {
buffer.append("<trendlines><line startValue='").append(
this.benchmarkValue).append(
"' color='91C728' displayValue='").append(
this.benchmarkName).append(
"' showOnTop='1' /></trendlines>");
}
return buffer.toString();
}
/**
* 從colors數組隨機選取一個顏色
*
* @return
*/
private String getColor() {
if (oneDimensionsList.size() <= 0) {
return this.colors[(new Random()).nextInt(this.colors.length)];
} else {
return this.colors[(new Random()).nextInt(oneDimensionsList.size())];
}
}
/**
* 生產隨機顏色
*
* @return
*/
private String getRandomColor() {
return (UUID.randomUUID().toString()).substring(0, 6);
}
/**
* 2維餅狀圖
*
* @return
*/
public String drawPie2D() {
return this.getDrawChart("Pie2D.swf", this.getOneDimensionsXmlData());
}
/**
* 3維餅狀圖
*
* @return
*/
public String drawPie3D() {
return this.getDrawChart("Pie3D.swf", this.getOneDimensionsXmlData());
}
/**
* 2維柱狀圖
*
* @return
*/
public String drawColumn2D() {
return this
.getDrawChart("Column2D.swf", this.getOneDimensionsXmlData());
}
/**
* 3維柱狀圖
*
* @return
*/
public String drawColumn3D() {
return this
.getDrawChart("Column3D.swf", this.getOneDimensionsXmlData());
}
/**
* 2維曲線圖
*
* @return
*/
public String drawLine2D() {
return this.getDrawChart("Line.swf", this.getOneDimensionsXmlData());
}
/**
* 3維曲線圖
* 這個方法暫時不能使用,因爲關於曲線圖一維數據的swf文件暫時沒找到
* @return
*/
public String drawLine3D() {
return this.getDrawChart("Line.swf", this.getOneDimensionsXmlData());
}
// ==============以下是多維數據柱狀圖,曲線圖===============
/**
* 多維2D柱狀圖
*
* @return
*/
public String drawColumn2DGroup() {
return this.getDrawChart("MSColumn2D.swf", this
.getManyDimensionsXmlData());
}
/**
* 多維2D曲線圖
*
* @return
*/
public String drawLine2DGroup() {
return this.getDrawChart("MSLine.swf", this.getManyDimensionsXmlData());
}
/**
* 多維3D柱狀圖
*
* @return
*/
public String drawColumn3DGroup() {
return this.getDrawChart("MSColumn3D.swf", this
.getManyDimensionsXmlData());
}
/**
* 多維3D曲線圖
*
* @return
*/
public String drawLine3DGroup() {
return this.getDrawChart("MSLine.swf", this
.getManyDimensionsXmlData());
}
// ==========get/set方法begin==============
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getXAxisName() {
return xAxisName;
}
public void setXAxisName(String axisName) {
xAxisName = axisName;
}
public String getYAxisName() {
return yAxisName;
}
public void setYAxisName(String axisName) {
yAxisName = axisName;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getJsPath() {
return jsPath;
}
public void setJsPath(String jsPath) {
this.jsPath = jsPath;
}
public String getSwfPath() {
return swfPath;
}
public void setSwfPath(String swfPath) {
this.swfPath = swfPath;
}
public String getDivId() {
return divId;
}
public void setDivId(String divId) {
this.divId = divId;
}
public String[] getColors() {
return colors;
}
public void setColors(String[] colors) {
this.colors = colors;
}
public String getMyChartName() {
return myChartName;
}
public void setMyChartName(String myChartName) {
this.myChartName = myChartName;
}
public List<Map<Object, Object>> getOneDimensionsList() {
return oneDimensionsList;
}
public void setOneDimensionsList(List<Map<Object, Object>> oneDimensionsList) {
this.oneDimensionsList = oneDimensionsList;
}
public Map<Object, Map<Object, Object>> getManyDimensionsMap() {
return manyDimensionsMap;
}
public void setManyDimensionsMap(
Map<Object, Map<Object, Object>> manyDimensionsMap) {
this.manyDimensionsMap = manyDimensionsMap;
}
public List<String> getXAxisNameList() {
return xAxisNameList;
}
public void setXAxisNameList(List<String> axisNameList) {
xAxisNameList = axisNameList;
}
public boolean isBenchmark() {
return benchmark;
}
public void setBenchmark(boolean benchmark) {
this.benchmark = benchmark;
}
public String getBenchmarkName() {
return benchmarkName;
}
public void setBenchmarkName(String benchmarkName) {
this.benchmarkName = benchmarkName;
}
public Object getBenchmarkValue() {
return benchmarkValue;
}
public void setBenchmarkValue(Object benchmarkValue) {
this.benchmarkValue = benchmarkValue;
}
// ================get/set方法end============
}
===================================================================
這樣一個封裝的fusionchart類就寫好了,然後怎麼使用呢?
這裏你使用struts還是servlet來控制流程都可以,我用的是struts。你只要看一下里面的方法是怎麼使用的就可以。
package com.testor.recursor.action.count;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.testor.recursor.tools.DrawDesigns;
public class FusionchartDrawAction implements ServletResponseAware, ServletRequestAware {
private HttpServletResponse response;
private HttpServletRequest request;
public String getCharts() {
DrawDesigns d = new DrawDesigns();
d.setCaption("查詢包數統計分析圖");
d.setXAxisName("指標發生時間");
d.setWidth(460);d.setHeight(350);
String str1 = d.drawLine3DGroup();
//這裏如果想要真實數據,可以自己寫,只要你寫好的數據封裝成list或者map的格式就可以。然後把參數傳到DrawDesigns這裏類裏就可以。
//我這裏沒有數據,因爲在DrawDesigns類裏面我用的是假數據,在verifyParams()這個方法裏的最下面就是我寫的假數據,被我註釋掉了。可以根據自己的需求隨便寫
System.out.println("打印出xml數據:" + str1);
request.setAttribute("draw0", str1);
return "success";
}
public void setServletResponse(HttpServletResponse arg0) {
this.response = arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
}
}
jsp:
<%@ page language="java" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>性能對比</title>
<link rel="stylesheet" type="text/css"
href="<%=path%>/scripts/ext-3.2.1/resources/css/ext-all.css" />
<script type="text/javascript" src="<%=path%>/scripts/jquery.js"></script>
<script type="text/javascript"
src="<%=path%>/scripts/ext-3.2.1/adapter/jquery/ext-jquery-adapter.js"></script>
<script type="text/javascript"
src="<%=path%>/scripts/ext-3.2.1/adapter/ext/ext-base.js"></script>
<script type="text/javascript"
src="<%=path%>/scripts/ext-3.2.1/ext-all.js"></script>
<script type="text/javascript"
src="<%=path%>/scripts/ext-3.2.1/examples/shared/examples.js"></script>
<script type="text/javascript"
src="<%=path%>/scripts/ext-3.2.1/ext-lang-zh_CN.js" charset="utf-8"></script>
///////////上面引用的js文件,你可以不用在乎,因爲這是我以前做東西引用的一些文件,對我們使用fusionchart不影響。你只關注下面的代碼就行。
</head>
<body style="background-color: #DFE8F6">
<div style="text-align: center">
${ draw0 } //這個就是後臺傳過來的參數。request.setAttribute("draw0", str1);
</div>
</body>
</html>
====================
這樣就成功了!可以根據這個思路自己隨便寫。
fusionchart效果圖: