一、搭建工作环境
1、搭建struts2的正常运行的工作环境
2、拷贝JFreeChart开发包中的jcommon.jar、jfreechart.jar
3、拷贝struts2/lib/struts2-jfreechart-plugin.jar
二、编写action类,代码如下.
//注意JFreeChart对象的名称固定为chart
//提供get方法,并在方法中对chart对象进行初始化
//部分代码为解决chart输出时候中文乱码的问题
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 6732701397007194574L;
//名称需要固定为chart,必须提供get方法,ChartResult会通过get方法读取当前action下的chart对象并进行输出
private JFreeChart chart;
public String execute() throws Exception {
return SUCCESS;
}
public JFreeChart getChart() {
/*饼状图
DefaultPieDataset ds = new DefaultPieDataset();
ds.setValue("开发人员45%", new Float(45));
ds.setValue("市场人员20%", new Float(20));
ds.setValue("管理人员10%", new Float(10));
ds.setValue("其他人员25%", new Float(25));
this.chart = ChartFactory.createPieChart(
"组织机构人员分布图",
ds,
true,
false,
true
);
chart.getTitle().setFont(new Font("Dialog",Font.BOLD,20));
chart.getLegend().setItemFont(new Font("Dialog",Font.BOLD,15));
PiePlot plot = (PiePlot)chart.getPlot();
plot.setLabelFont(new Font("Dialog",Font.ITALIC,10));
*/
//柱状图
DefaultCategoryDataset dataset=new DefaultCategoryDataset(); //创建dataset
dataset.setValue(47, "", "张三");
dataset.setValue(154, "", "李四");
dataset.setValue(74, "", "王五");
dataset.setValue(121, "", "赵六");
chart=ChartFactory.createBarChart(
"网络投票统计图", //标题
"选手", //x轴标题
"得票数", //y轴标题
dataset, //dataset
PlotOrientation.VERTICAL, //图标方向
true, //是否成成图形
true, //是否生成工具
true //是否生成url链接
);
chart.getLegend().setVisible(false);
chart.getTitle().setFont(new Font("Dialog",Font.BOLD,20));
chart.getLegend().setItemFont(new Font("Dialog",Font.BOLD,15));
CategoryPlot plot = (CategoryPlot)chart.getPlot();
CategoryAxis x = plot.getDomainAxis();
x.setLabelFont(new Font("Dialog",Font.BOLD,15));
x.setTickLabelFont(new Font("Dialog",Font.BOLD,15));
ValueAxis y = plot.getRangeAxis();
y.setLabelFont(new Font("Dialog",Font.BOLD,15));
return chart;
}
}
三、在struts.xml文件中配置此action,配置如下.
/**
* struts2的action默认的返回结果为forward
* 必须定义result-type为chart类型,class类来自struts2-jfreechart-plugin.jar,可以提供输出图片大小参数
* 当前action的返回结果type=chart类型
*/
<package name="default" namespace="/" extends="struts-default">
<result-types>
<result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult">
<param name="height">400</param>
<param name="width">500</param>
</result-type>
</result-types>
<action name="test" class="action.TestAction">
<result name="success" type="chart"></result>
</action>
</package>
四、访问http://localhost:8080/web_Project_Name/test.action,看到chart的输出图片,整合完毕!
struts2整合JFreeChart(精简版)
最新推荐文章于 2013-11-26 16:36:00 发布