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页面显示出所对应的折线图:
JFreeChart sturt2
最新推荐文章于 2018-10-22 23:07:00 发布