JFreeChart sturt2

2012-01-18 18:14 整合Struts2跟JFreeChart生成折线图显示在jsp页面这两天做一个Struts2跟JFreeChart整合的图表。不多说,直接进入正题:

首先,还是看下工程目录:

目录就是一般的web project目录,主要是看下所要导入的架包。JFreeChart的架包可在其官网下载最新版本(官网地址:http://sourceforge.net/projects/jfreechart/files/1.JFreeChart/)。这里除了JFreeChart架包以外还要导入Struts2中跟JFreeChart交互的插件包:struts2-jfreechart-plugin-2.0.11.jar,还有一开始的几个commons-xx的几个架包貌似也不能少,当在配置的时候发现这几个少了部署的时候也会报错,具体是哪个我也没有深入研究。

其次,就是web.xml的配置了,以前我配置struts2的web.xml直接就是这样:

         <filter>
                  <filter-name>struts</filter-name>
                 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
       </filter>    
      <filter-mapping>
                <filter-name>struts</filter-name>
                <url-pattern>/*</url-pattern>
     </filter-mapping>

可跟JFreeChart整合在后面配置Strtus.xml的时候再部署还是会报错,具体什么原因我也不知道,后来在网上看了这种配置方式:

      <filter>
          <filter-name>struts-prepare</filter-name>
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
    </filter>
    <filter>
        <filter-name>struts-execute</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts-execute</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

这样配置就没有问题了,神马原因我也不知道。

然后,就是写后台方法了:

1.写一个生成折线图的工具类:

package cn.infocore.www;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;

public class CreateLinechart {
    /**
     * 图片保存的根目录
     * @param filename
     * @return
     */
    public String Savepath(){
        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String testpath = path.substring(0,path.lastIndexOf("WEB-INF"));
        String filepath = testpath+"images/";
        System.out.println(filepath);
        return filepath;//Tomcat的中webapps目录下项目的images文件夹
    }
    
    /**
     *  柱状图,折线图 数据集 方法
     */
    public CategoryDataset getBarData(double[][] data, String[] rowKeys,     
            String[] columnKeys) {     
        return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);     
    
    }
    private void isChartPathExist(String chartPath) {     
        File file = new File(chartPath);     
        if (!file.exists()) {     
            file.mkdirs();     
        // log.info("CHART_PATH="+CHART_PATH+"create.");     
        }
             
    }
 
    /**
     * 折线图样式
     * @param chartTitle
     * @param x
     * @param y
     * @param xyDataset
     * @param charName
     * @return
     */
     public JFreeChart createTimeXYChar(String chartTitle, String x, String y,     
                CategoryDataset xyDataset, String charName) {     
            JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,     
                    xyDataset, PlotOrientation.VERTICAL, true, true, false);     
            chart.setTextAntiAlias(false);     
            chart.setBackgroundPaint(Color.RED);     
            // 设置图标题的字体重新设置title     
            Font font = new Font("宋体", Font.BOLD, 20);     
            TextTitle title = new TextTitle(chartTitle);     
            title.setFont(font);     
            chart.setTitle(title);     
            // 设置面板字体     
            Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);     
            chart.setBackgroundPaint(Color.WHITE);     
            CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();     
            // x轴 // 分类轴网格是否可见     
            categoryplot.setDomainGridlinesVisible(true);     
            // y轴 //数据轴网格是否可见     
            categoryplot.setRangeGridlinesVisible(true);     
            categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩     
            categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩     
            categoryplot.setBackgroundPaint(Color.lightGray);     
            // 设置轴和面板之间的距离     
            // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));     
            CategoryAxis domainAxis = categoryplot.getDomainAxis();     
            domainAxis.setLabelFont(labelFont);// 轴标题     
            domainAxis.setTickLabelFont(labelFont);// 轴数值     
            domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD); // 横轴上的     
            // Lable     
            // 45度倾斜     
            // 设置距离图片左端距离     
            domainAxis.setLowerMargin(0.0);     
            // 设置距离图片右端距离     
            domainAxis.setUpperMargin(0.0);             
            NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();     
            numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());     
            numberaxis.setAutoRangeIncludesZero(true);     
            // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!     
            LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();     
            //XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) categoryplot  
           // .getRenderer();//改变曲线颜色
            lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见     
            lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见  
            // 显示折点数据     
           /* lineandshaperenderer.setBaseItemLabelGenerator(new     
            StandardCategoryItemLabelGenerator());     
            lineandshaperenderer.setBaseItemLabelsVisible(true);  */        
            //图片路径
            FileOutputStream fos_jpg = null;     
            try {     
                isChartPathExist(Savepath());     
                String chartName = Savepath() + charName;     
                fos_jpg = new FileOutputStream(chartName);     
        
                // 将报表保存为JPG文件     
                ChartUtilities.writeChartAsJPEG(fos_jpg, chart, 500, 510);             
                   
            } catch (Exception e) {     
                e.printStackTrace();     
                return null;     
            } finally {     
                try {     
                    fos_jpg.close();     
                    System.out.println("create time-createTimeXYChar.");     
                } catch (Exception e) {     
                    e.printStackTrace();     
                }     
            }
            return chart;     
     }   
}

 

2.编写jsp页面需要调用的Action控制器

package cn.infocore.www;

import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class LineChartView extends ActionSupport{
    private static final long serialVersionUID = 1L;
    private JFreeChart chart;
    
    public String LineChartView() {
        double[][] data = new double[][]{     
                {372, 766, 223, 540, 126},     
                {325, 521, 210, 340, 106},     
                {332, 256, 523, 240, 526}     
            };     
            String[] rowKeys = {"葡萄", "梨子", "苹果"};     
            String[] columnKeys = {"北京", "上海", "广州", "成都", "深圳"};
        try {
            //zlist,dlist, nlist赋值到HorizontalItemLabelDome里 这个jfreechart中的一个dome
            CreateLinechart demo = new CreateLinechart();
            HttpServletResponse response = (HttpServletResponse) ActionContext
                    .getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
            response.setContentType("image/jpg");
            chart = demo.createTimeXYChar("折线图数据分析", "城市", "品种", demo.getBarData(data, rowKeys, columnKeys), "lineAndShap.jpg");
            ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart,
                    500, 400, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return "horizontalItemLabelView";
        return "success";
    }

    public JFreeChart getChart() {
        return chart;
    }

    public void setChart(JFreeChart chart) {
        this.chart = chart;
    }
}
接着,就是配置Struts.xml和折线图的xml文件了,

1.Struts.xml文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-jfreechart.xml"></include>    
    <package name="redarmy" namespace="/csdn" extends="struts-default">
        <global-results>
        <result name="input">/index.jsp</result>
        </global-results>
    </package>
</struts>

2.在src目录下再新建一个struts-jfreechart.xml文件,用于配置JFreechart:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="lineChart" extends="jfreechart-default,struts-default"
        namespace="/lineChart">
        <result-types>
            <result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult"></result-type>
        </result-types>
          <action name="lineChart" class="cn.infocore.www.LineChartView">
              <result type="chart"> 
                   <param name="width">400</param>
                   <param name="height">700</param>
            </result>
        </action>
    </package>
</struts>

最后,在index.jsp页面里编写调用action的代码:

<img style="margin:auto;"  src="${pageContext.request.contextPath}/lineChart/lineChart!LineChartView.action"/>

至此,所有的准备工作都完成了,将项目部署到Tomcat里面发布之后输入url:

http://192.168.1.196:8080/JFreeChart/index.jsp就能在jsp页面显示出所对应的折线图:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要配置JFreeChart,您需要按照以下步骤进行操作: 1. 首先,您需要从JFreeChart的官方网站(http://www.jfree.org/jfreechart/download.html)下载最新版本的JFreeChart。 2. 在下载页面上,您将看到三个选项可供下载:JFreeChart、Documentation和JCommon。如果您只需要使用JFreeChart来生成统计图表,您只需要下载JFreeChart项目的压缩文件即可。如果您需要查看JFreeChart的API文档,您可以下载Documentation。而JCommon是JFreeChart所依赖的类库文件,如果您已经有了这些类库文件,那么可以选择不下载。 3. 下载完JFreeChart之后,您可以将其解压缩到您的项目目录中。 4. 接下来,您需要将JFreeChart的JAR文件添加到您的项目的构建路径中。具体操作方式取决于您使用的开发工具和构建系统。在大多数情况下,您只需将JAR文件拷贝到您的项目的lib目录下,并将其添加到构建路径中即可。 5. 一旦您完成了JFreeChart的配置,您就可以开始使用它来生成统计图表了。根据您的需求,您可以使用JFreeChart来生成各种类型的图表,例如饼图、柱状图、散点图、时序图、甘特图等等。只需按照JFreeChart的API文档提供符合其所需格式的数据,即可自动生成相应的图表。这些图表可以直接输出为图片文件,也可以导出为PDF或Excel文档。 希望这些步骤能够帮助您成功配置和使用JFreeChart来生成统计图表。如果您需要更详细的说明,请参考JFreeChart的官方文档或社区资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值