使用open flash chart製做報表

 http://sarin.iteye.com/blog/685354這篇文章對open flash chart與struts2的整合使用作了詳細的介紹,可是按照文章裏面的內容進行實際操做的時候,卻報了open flash char io error Loading test data Error #2032 的錯,通過分析,緣由我忘記了引入jofc2其所依賴的xstream包......在這裏,須要注意的是這兩個JAR包版本號的問題,我使用的是jofc2-1.0-0.jar和xstream-1.3.1.jar。javascript

               項目按照Struts2的開發標準搭建,而後把OFC開發所需的flash文件,頁面顯示Flash的支持文件swfobject.js放到發佈目錄的相應位置,再將jofc2和其依賴的xstream的jar包放到WEB-INF/lib下並加入編譯路徑便可。 html

    需求仍是按照那篇博客文章中寫的那樣:記錄系統訪問用戶所使用的瀏覽器並用圖表顯示。那麼須要在數據庫中記錄這樣的信息,如圖所示: 

 

1----    首先是Action的定義,代碼以下:java

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import jofc2.model.Chart;
import jofc2.model.axis.Label;
import jofc2.model.axis.XAxis;
import jofc2.model.axis.YAxis;
import jofc2.model.elements.BarChart;
import jofc2.model.elements.LineChart;

/**   
 * 
 * @Project gun
 * @Package action.chart
 * @Class TestAction
 */
public class TestAction extends ActionSupport{
	private Chart ofcChart;  
    public Chart getOfcChart() {  
        return ofcChart;  
    }  
    public String showChart() throws Exception{  
        //y軸數據集合-使用數量  
        List<Number> dataSet = new ArrayList<Number>();  
        for(int i=1; i<=12;i++) {
        	dataSet.add((Integer)i);
        }
        //x軸數據集合-瀏覽器類型  
        List<Label> xLabel = new ArrayList<Label>();  
        //獲取須要顯示的數據集  
        List browserList = new TestDAO().get();  
        for (int i = 0; i < browserList.size(); i++) {  
            Test map = (Test) browserList.get(i);  
            //填充x軸  
            dataSet.add((Integer) map.getStatCount());  
            //填充y軸  
            xLabel.add(new Label((String) map.getStatVar()));  
        }  
        //設置X軸內容  
        XAxis labels = new XAxis();  
        labels.addLabels(xLabel);  
        //設置Y軸顯示值域:Range的三個參數含義爲:座標最小值,最大值和步進值  
        YAxis range = new YAxis();  
        range.setRange(0, 200, 10);  
        //OFC折線圖設置  
//      LineChart lineChart = new LineChart(LineChart.Style.NORMAL);
        //柱狀圖
        BarChart lineChart=new BarChart(BarChart.Style.GLASS); 
        lineChart.addValues(dataSet);  
        lineChart.setColour("#6666FF");  
        lineChart.setText("使用者數量");  
        //圖表設置  
        ofcChart = new Chart("用戶瀏覽器使用量分佈");  
        ofcChart.setXAxis(labels);  
        ofcChart.setYAxis(range);  
        ofcChart.addElements(lineChart);  
  
        return SUCCESS;  
    }  

}

  2  DAO類,從數據庫中獲取數據,另外還定義了一個Bean類Testsql

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gun.base.db.DBConnection;

/**
 * 從數據庫中取得所需的數據
 * 
 * @Project gun
 * @Package action.chart
 * @Class TestDAO
 */
public class TestDAO {

	public List get() throws Exception {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		String querySQL = "select statCount, statVar from test where statType='broeser'";
		List list = new ArrayList();
		try {
			conn = DBConnection.getConnection();
			stmt = conn.prepareStatement(querySQL);
			rs = stmt.executeQuery();
			System.out.println("OK");
			while (rs.next()) {
				Test test = new Test();
				test.setStatCount(rs.getInt("statCount"));
				test.setStatVar(rs.getString("statVar"));
				list.add(test);
			}
			return list;
		} catch (SQLException e) {
			throw new Exception("根據主鍵查詢信息失敗,錯誤信息:" + e.toString());
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					DBConnection.releaseConnection(conn);
			} catch (SQLException e) {
				throw new Exception("關閉數據庫失敗,錯誤信息:" + e.toString());
			}
		}
	}
}

/**
 * 請在此處填寫類的描述
 * 
 * @Project gun
 * @Package action.chart
 * @Class Test
 */
public class Test {
	private String statVar;

	private int statCount;

	public String getStatVar() {
		return statVar;
	}

	public void setStatVar(String statVar) {
		this.statVar = statVar;
	}

	public int getStatCount() {
		return statCount;
	}

	public void setStatCount(int statCount) {
		this.statCount = statCount;
	}

}

3    最後定義了TestResult類,繼承於StrutsResultSupport,用於生成json格式的數據。數據庫

import jofc2.model.Chart;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionInvocation;

public class TestResult extends StrutsResultSupport {
	private static final String ENCODING = "GBK";

	private static final long serialVersionUID = 4702848904993212381L;

	@Override
	protected void doExecute(String arg0, ActionInvocation inv)
			throws Exception {
		Chart chart = (Chart) inv.getStack().findValue("ofcChart");
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json-rpc;charset=" + ENCODING);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Pragma", "No-cache");
		String json = chart.toString();
		System.out.println(json.toString());
		response.setContentLength(json.getBytes(ENCODING).length);
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}
}

4  如今須要在struts.xml配置文件中配置Action,以下:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<package name="gun" extends="json-default">

		<result-types>
			<result-type name="ofc" class="action.chart.TestResult" />
		</result-types>

		<action name="test" class="action.chart.TestAction" method="showChart">
			<result type="ofc" name="success">
			</result>
		</action>

	</package>
</struts>

5   JSP頁面很簡單,只須要寫一些簡單的JS代碼便可:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'cbar.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<script type="text/javascript" src="openflashchart/js/swfobject.js"></script>
<script type="text/javascript">  
    var flashvars = {"data-file":"test.action"};  
    var params = {menu: "false",scale: "noScale",wmode:"opaque"};  
    swfobject.embedSWF("openflashchart/open-flash-chart.swf", "my_chart", "900", "500", "9.0.0",  
    "expressInstall.swf",flashvars,params);  
</script>
</head>

<body>
	<table align="center">
		<tr>
			<td><div id="my_chart"></div></td>
		</tr>
	</table>
</body>
</html>

   最後運行程序,結果以下:

PS:第一次發表博文,寫做能力有限,請多海涵...express

相關文章
相關標籤/搜索