Dorado 5 : 12.3.JfreeChart图表-条状图 (T22)

概述

本示例用来展示dorado与JfreeChart的结合,用来展示JfreeChart的条状图。除JFreeChart,本示例还采用了Cewolf,可以看知识点部分。本示例链接如下:

 

准备工作

步骤1:新建一工程timeseries,并且配置好数据库,具体步骤参考3.1.2节。
步骤2:下载cewolf。下载链接如下:

步骤3:解压下载的cewolf-1.0-bin-src.zip,拷贝cewolf/lib文件夹下面的如下文件到您web工程的web-inf/lib目录下面:jfreechart-.jar、jcommon-.jar、commons-logging.jar、cewolf.jar、batik-xml.jar、batik-util.jar、batik-svggen.jar、batik-dom.jar、batik-awt-util.jar。
如果需要在基于mozilla的浏览器下面使用image maps的功能的话,必须拷贝/etc/overlib.js到web根目录下面。
另外,拷贝/etc/cewolf.tld拷贝到工程的web-inf里面。
步骤4:在web-inf的web.xml文件下面添加如下代码:

 <servlet> 
 <servlet-name>CewolfServlet</servlet-name> 
 <servlet-class>de.laures.cewolf.CewolfRenderer</servlet-class> 
 <!-- sets storage implementation --> 
 <init-param> 
 <param-name>storage</param-name> 
 <param-value>de.laures.cewolf.storage.TransientSessionStorage</param-value> 
 </init-param> 
 <load-on-startup>1</load-on-startup> 
 </servlet> 
 <servlet-mapping> 
 <servlet-name>CewolfServlet</servlet-name> 
 <url-pattern>/cewolf/*</url-pattern> 
 </servlet-mapping>

开发步骤

添加Dataset

步骤1:在Source下新建一文件夹,文件夹名为timeseries。在timeseries下面添加一Common ViewModel,文件名为TimeSeriesView。
步骤2:添加一AutoSqlDataset,选择Employee表格,选择所有字段。AutoSqlDataset属性设置如下:

属性

id

dataset1

originTable

Employee

pageSize

8

readOnly

true

 

添加DataTable、ListDropDown和PagePolit

步骤1:添加一DataTable,属性设置如下:

属性

dataset

dataset1

height

100%

id

table1

width

100%

选择table1,点击字段生成按钮。
步骤2:添加一PagePolit,属性设置如下:

属性

dataset

dataset1

id

pagepilot1

步骤3:添加一ListDropDown,属性设置如下:

属性

id

dropdownSex

mapValue

true

autoDropDown

true

步骤4:为dropdownSex添加2个DropDownItem,第一个字段name为"男",value为"true",第二个字段name为"女",value为"false"。
步骤5:设置dataset1的字段sex的DropDown为dropdownSex。

添加DatasetProducer和显示图表的Jsp

步骤1:在timeseries文件夹下面,添加一Simple Class,类名为TimeSeriesProducer,代码如下:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.TimeSeriesDataItem;
import com.bstek.dorado.common.DoradoContext;
import com.bstek.dorado.data.PagingHelper;
import com.bstek.dorado.data.db.DBStatement;
import com.bstek.dorado.utils.variant.VariantSet;
import de.laures.cewolf.DatasetProduceException;
import de.laures.cewolf.DatasetProducer;
import de.laures.cewolf.links.XYItemLinkGenerator;
public class TimeSeriesProducer implements DatasetProducer, XYItemLinkGenerator {
    public String getProducerId() {
        return null;
    }
    public boolean hasExpired(Map params, Date since) {
        return true;
    }
    public Object produceDataset(Map params) throws DatasetProduceException {
        TimeSeries manTime = new TimeSeries("男士工资走势曲线", Day.class);
        TimeSeries womanTime = new TimeSeries("女士工资走势曲线", Day.class);
        DoradoContext context = DoradoContext.getContext();
        String pageIndex = context.getParameter("pageIndex");
        String pageSize = context.getParameter("pageSize");
        if (pageIndex != null && pageSize != null) {
            DBStatement stmt = new DBStatement();
            stmt.setDataSource("doradosample");
            List result = new ArrayList();
            String sql = "select count(*) as c from employee";
            stmt.setSql(sql);
            PagingHelper page = new PagingHelper();
            try {
                VariantSet vs = stmt.query();
                int recordCount = vs.getInt("c");
                page.setPageIndex(Integer.parseInt(pageIndex));
                page.setPageSize(Integer.parseInt(pageSize));
                page.setTotalRow(recordCount);
                sql = "select employee_id,employee_name,birthday,salary,sex from employee";
                stmt.setSql(sql);
                List list = stmt.queryForList();
                for (int i = page.getFromIndex(); i < page.getFromIndex()
                        + page.getPageSize(); i++) {
                    if (i > list.size() - 1) {
                        break;
                    }
                    VariantSet variantSet = (VariantSet) list.get(i);
                    result.add(variantSet);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new IllegalArgumentException("数据处理异常.");
            } finally {
                stmt.close();
            }
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < result.size(); i++) {
                VariantSet vSet = (VariantSet) result.get(i);
                boolean sex = vSet.getBoolean("sex");
                double salary = vSet.getDouble("salary");
                String birthday = vSet.getString("birthday");
                try {
                    Date date = sd.parse(birthday);
                    if (sex) {
                        manTime.add(new Day(this
                                .getDatePartByFormat("dd", date), this
                                .getDatePartByFormat("MM", date), this
                                .getDatePartByFormat("yyyy", date)), salary);
                    } else {
                        womanTime
                                .add(new Day(this.getDatePartByFormat("dd",
                                        date), this.getDatePartByFormat("MM",
                                        date), this.getDatePartByFormat("yyyy",
                                        date)), salary);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("数据处理异常.");
                }
            }
        }
        TimeSeriesCollection tc = new TimeSeriesCollection();
        tc.addSeries(womanTime);
        tc.addSeries(manTime);
        return tc;
    }
    private int getDatePartByFormat(String pattern, Date d) {
        SimpleDateFormat sd = new SimpleDateFormat(pattern);
        return Integer.parseInt(sd.format(d));
    }
    public String generateLink(Object data, int series, int item) {
        TimeSeriesCollection timeseries = (TimeSeriesCollection) data;
        TimeSeries ser = timeseries.getSeries(series);
        StringBuffer sb = new StringBuffer();
        TimeSeriesDataItem it = ser.getDataItem(item);
        double tmp = ((Double) it.getValue()).doubleValue();
        sb.append("javascript:");
        sb.append("var record = parent.dataset1.getFirstRecord();");
        sb.append("while (record) {");
        sb.append("var a=record.getValue('salary');");
        sb.append("if(a=='" + tmp + "'){");
        sb.append("parent.dataset1.setCurrent(record);");
        sb.append("break;");
        sb.append("}");
        sb.append("record = record.getNextRecord();");
        sb.append("}");
        sb.append("alert('" + tmp + "');");
        return sb.toString();
    }
}

 

步骤2:添加一Simple Class,类名为TimeSeriesPostProcess,代码如下:

import java.text.SimpleDateFormat;
import java.util.Map;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import de.laures.cewolf.ChartPostProcessor;
public class TimeSeriesPostProcess implements ChartPostProcessor {
    public void processChart(Object chart, Map params) {
        JFreeChart obj = (JFreeChart) chart;
        XYPlot plot = obj.getXYPlot();
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("yyyy/MM/dd"));
        axis.setVerticalTickLabels(true);
    }
}

步骤3:添加显示图表的Jsp文件,文件名为timeseries-chart.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@ taglib uri='/WEB-INF/cewolf.tld' prefix='cewolf'%> 
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 </head> 
 <body style="margin: 0"> 
 <jsp:useBean id="timeSeriesPostProcessor" class="timeseries.TimeSeriesPostProcess"/> 
 <jsp:useBean id="timeSeriesProducer" class="timeseries.TimeSeriesProducer"/> 
 
 <cewolf:chart id="timeSeries" type="timeseries" title="员工生日与工资" xaxislabel="员工生日" yaxislabel="员工工资"> 
 <cewolf:chartpostprocessor id="timeSeriesPostProcessor" /> 
 <cewolf:data> 
 <cewolf:producer id="timeSeriesProducer" /> 
 </cewolf:data> 
 </cewolf:chart> 
 <cewolf:img chartid="timeSeries" height="300" width="1000" renderer="/cewolf"> 
 <cewolf:map linkgeneratorid="timeSeriesProducer" /> 
 </cewolf:img> 
 </body> 
 </html>

步骤4:在TimeSeriesView的onLoad事件中写入如下代码:

var pageIndex=dataset1.getPageIndex(); 
var pageSize=dataset1.getPageSize(); 
var url="timeseries-chart.jsp?pageIndex="pageIndex"&pageSize="pageSize""; 
window.open(url,"charFrame");

步骤5:在dataset1的afterFlushData事件中写入如下代码:

var pageIndex=dataset1.getPageIndex(); 
var pageSize=dataset1.getPageSize(); 
var url="timeseries-chart.jsp?pageIndex="pageIndex"&pageSize="pageSize""; 
window.open(url,"charFrame");

创建Jsp页面

为TimeSeriesView生成Jsp页面,文件名为time-series-view.jsp,对其进行编辑以后,最后结果如下:

<%@ page contentType="text/html; charset=UTF-8" %> 
<%@ taglib uri="http://www.bstek.com/dorado" prefix="d" %> 
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 </head> 
 <body style="margin: 0; overflow: hidden"> 
 <d:View config="timeseries.TimeSeriesView"> 
 <d:SplitPanel id="splitpanel2" orientation="vertical" position="270" width="100%" height="100%" showButtons="true"> 
 <d:Layout type="border"> 
 <d:Pane position="center"> 
 <d:DataTable id="table1" /> 
 </d:Pane> 
 <d:Pane position="bottom"> 
 <d:PagePilot id="pagepilot1" /> 
 </d:Pane> 
 </d:Layout> 
 <d:Splitter /> 
 <iframe name="charFrame" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="0"></iframe> 
 </d:SplitPanel> 
 </d:View> 
 </body> 
 </html>

浏览运行效果

启动服务器以后,浏览time-series-view.jsp,效果如下:

对表格中的数据翻页以后,可以看到下方的条状图不断变化。

知识点

本节知识点主要在于JFreeChart与Cewolf的相关知识。关于JFreeChart,可以查看如下链接:

关于Cewolf,可以查看如下链接: