六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 153|回复: 0

使用fusioncharts实现数据库的动态数据交互

[复制链接]

升级  72%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
36
 楼主| 发表于 2013-2-6 10:55:20 | 显示全部楼层 |阅读模式
线简单介绍一下FusionCharts,这是一款动态的制作报表的工具,主要通过XML数据和SWF文件进行交互,实现类似于flash的非常漂亮的报表。下面就做一个Demo,简要介绍一下啊fusioncharts的功能,以及如何实现一个完整动态数据的交互。
   首先下载FusionCharts的官方API发布包,我做这个例子的时候是V3.1下载后,在MyEclipse下新建一个Web工程。然后将发布包中的Charts文件夹拷贝到WebRoot下,这里面都是我们接下来要做图的时候用到的一些swf文件。接着还需要一个JS文件,是JSClass文件夹下的FusionCharts.js文件,将它拷贝到WebRoot下的ChartsJs文件夹下。由于我这个项目是结合struts1还有spring加上JPA做的。所以大家先有个基本的认识。然后在WEB-INF下建立两个目录,一个叫fusion、一个叫common,等会我们会用到。找到发布包的\Code\JSP\Includes目录下,将FusionCharts.jsp文件拷贝到common文件夹下。
   准备环境完成了,那么我们下面就开始做了。
   首先说我想做什么内容。主要是展示2004、2005、2006、2007四年的一个油品的销售统计,用柱状图来表示,然后点击每一个柱子,会在右边显示出饼状的上半年的各个月份的销售比例。
   首先建立实体Bean,代码如下
import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;import com.zxyg.bean.orgnization.Employee;/** * 年销售统计 * @author Lan *  */@Entity@Table(name = "t_yearunits")public class YearUnits {private Integer id;private String year;private Float units;private Set<MonthUnits> months = new HashSet<MonthUnits>();@OneToMany(mappedBy="year", cascade=CascadeType.REFRESH)public Set<MonthUnits> getMonths() {return months;}public void setMonths(Set<MonthUnits> months) {this.months = months;}@Id @GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(length=4, nullable=false)public String getYear() {return year;}public void setYear(String year) {this.year = year;}@Column(length=5, nullable=false)public Float getUnits() {return units;}public void setUnits(Float units) {this.units = units;}}

import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;/** * 月销售统计 * @author Lan *  */@Entity@Table(name = "t_monthunits")public class MonthUnits {private Integer id;private String month;private Float units;private YearUnits year;@ManyToOne(cascade=CascadeType.REFRESH)@JoinColumn(name="year_id")public YearUnits getYear() {return year;}public void setYear(YearUnits year) {this.year = year;}@Id @GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(length=4, nullable=false)public String getMonth() {return month;}public void setMonth(String month) {this.month = month;}@Column(length=5, nullable=false)public Float getUnits() {return units;}public void setUnits(Float units) {this.units = units;}}
这分别是年销售统计和月销售统计的实体Bean
由于Service层的东西都在底层封装好了,所以建立好表后,手动添加一些数据就好了。
接下来是Action层的代码,首先是针对年销售突击的Action的代码
import java.io.PrintWriter;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction;import org.springframework.stereotype.Controller;import com.zxyg.bean.report.MonthUnits;import com.zxyg.bean.report.YearUnits;import com.zxyg.service.report.MonthUnitsService;import com.zxyg.service.report.YearUnitsService;/** * 年销售统计图表 * @author Lan * */@Controller("/year/units/report")public class YearUnitsAction extends Action {@Resource private YearUnitsService yearUnitsService;public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {//年销售统计StringBuilder strXML1 = new StringBuilder("");strXML1.append("<?xml version='1.0' encoding='GBK'?><chart palette='2' maxColWidth='70' rotateYAxisName='0' caption='油品年销售统计' " + "startingAngle='125' shownames='1' showvalues='0' numberPrefix='$'>");List<YearUnits> yearunits = yearUnitsService.getScrollData().getResultlist();for(YearUnits units : yearunits) {strXML1.append("<set label='" + units.getYear() + "' value='" + units.getUnits()+ "'link='JavaScript:myJS(" + units.getYear().substring(0, 4) + ")'/>");}strXML1.append("</chart>");request.setAttribute("strXML1", strXML1.toString());return mapping.findForward("report");}}
这里的钻取要用到ajax技术,所以接下来是月销售统计的数据钻取
import java.io.PrintWriter;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.springframework.stereotype.Controller;import com.zxyg.bean.report.MonthUnits;import com.zxyg.service.report.MonthUnitsService;/** * 月销售统计图表 * @author Lan * */@Controller("/month/units/report")public class MonthUnitsAction extends Action {@Resource private MonthUnitsService monthUnitsService;@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {response.setContentType("text/html;charset=utf-8");response.setHeader("Cache-Control", "no-cache");PrintWriter out = response.getWriter();String year = request.getParameter("year");if(year != null && !"".equals(year)) {out.print("<chart palette='2' rotateYAxisName='0' caption='上半年销售历史' xAxisName='月份' refreshInterval='60'"           +" yAxisName='Units' showValues='0'>");List<MonthUnits> monthunits = monthUnitsService.getMonthUnitsByYear(year.trim());for(int i=0; i<monthunits.size(); i++) {MonthUnits monthUnits = monthunits.get(i);out.print("<set label='" + monthUnits.getMonth()+ "' value='" + monthUnits.getUnits()+ "' />");}out.print("</chart>");}return null;}}
最后是页面的代码,struts1的配置我就不写了,反正是定向到WEB-INF下的fusion下的
year_units_report.jsp下
页面代码如下
<%@ page contentType="text/html;charset=UTF-8" %><%@ include file="/WEB-INF/page/share/taglib.jsp" %><%@ include file="/WEB-INF/page/share/FusionCharts.jsp" %><html><head><title>报表显示</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" href="/css/vip.css" type="text/css"><script language="JavaScript" src="/ChartsJs/FusionCharts.js"></script><script LANGUAGE="JavaScript">var xmlHttpRequest;    function myJS(myVar) {    initRequest(myVar);    }        //初始化xmlHttpRequest对象    function initRequest(myVar) {    if(window.XMLHttpRequest) {try {xmlHttpRequest = new XMLHttpRequest();if(xmlHttpRequest.overrideMimeType) {xmlHttpRequest.overrideMimeType("text/html;charset=UTF-8");}}catch (e) {}}else if(window.ActiveXObject) {try {xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {try {xmlHttpRequest = new ActiveXObject("Msxml2.XMLHttp");} catch (e) {try {xmlHttpRequest = new ActiveXObject("Msxml3.XMLHttp");} catch (e) {}}}}    verify(myVar);    }        //准备传输数据    function verify(myVar) {    var url = "/month/units/report.do";    xmlHttpRequest.onreadystatechange = callback;    xmlHttpRequest.open("POST", url, true);    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    xmlHttpRequest.send("year=" + myVar);    //xmlHttpRequest.send(null);    }        //定义回调函数    function callback() {    if(xmlHttpRequest.readyState == 4) {    if(xmlHttpRequest.status == 200) {    var responseText = xmlHttpRequest.responseText;    createHTML3D(responseText);    }    }    }        //创建子数据图    function createHTML3D(data) {    var myChart = new FusionCharts("/Charts/Pie3D.swf", "myChartId", "500", "300", "0", "0");    myChart.setDataXML(data);    myChart.render("chartdiv");    }</script></head><body bgcolor="#FFFFFF" text="#000000" marginwidth="0" marginheight="0"><%                   String strXML1 = (String)request.getAttribute("strXML1");    if(strXML1 != null && !"".equals(strXML1)) {    String chartHTML1 = createChartHTML("/Charts/Column3D.swf",  "", strXML1, "YearUnits", 500, 300, false); %> <span>   <%=chartHTML1%>   </span> <%     } %>  <span id="chartdiv"> </span></body></html>
最后图的效果如下


这样就做到了动态数据交互钻取,页面不刷新。达到了预期的效果。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表