struts2+MySQL+jfreechart
来源:程序员人生 发布时间:2015-01-30 08:30:10 阅读次数:4971次
1.所需要的jar包如图1所示
2.工程目录的格式如图2所示
2.新建配置文件(struts-jfreechart.xml)
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts⑵.0.dtd">
<struts>
<package name="jFreeChartDemonstration" extends="struts-default" namespace="/jfreechart">
<result-types>
<result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult"></result-type>
</result-types>
<action name="JFreeChartAction" class="com.lyf.jf.JFreeChartAction">
<result type="chart">
<param name="width">400</param>
<param name="height">300</param>
</result>
</action>
</package>
</struts>
说明:这里只需要说明下struts-jfreechart.xml,这里直接调用已写好的类ChartResult,这个类是继承自com.opensymphony.xwork2.Result,传入生成图片大小的参数width和height就能够了。
3.新建struts.xml文件
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts⑵.0.dtd">
<struts>
<include file="struts-jfreechart.xml" />
</struts>
4.修改web.xml文件
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5.新建index.jsp页面
<%@ page language="java" pageEncoding="utf⑻"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>2010计算机编程语言市场份</title>
</head>
<body>
<h2>
<center>2010计算机编程图书销量统计图</center>
</h2>
<center>
<img src="<s:url value='jfreechart/JFreeChartAction.action'/>" />
</center>
</body>
</html>
6.新建JFreeChartAction继承ActionSupport,生成JFreeChart对象并保存到chart中
package com.lyf.jf;
import java.awt.Color;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import com.opensymphony.xwork2.ActionSupport;
public class JFreeChartAction extends ActionSupport {
static final long serialVersionUID = 0L;
/**
* JFreeChart对象chart,注意这个名称是固定的。
* 供ChartResult调用->ActionInvocation.getStack().findValue("chart")
*/
private JFreeChart chart;
// 定义图表的宽度
private Integer width;
// 定义图表的长度
private Integer height;
@Override
public String execute() throws Exception {
width = 400;
height = 300;
// 生成JFreeChart对象
makePieChart();
return SUCCESS;
}
// 生成饼图
public void makePieChart() {
// 设置数据
PieDataset data;
data=createDataset();
//解决乱码问题(不能显示中文的问题)
StandardChartTheme mChartTheme = new StandardChartTheme("CN");
mChartTheme.setLargeFont(new Font("黑体", Font.BOLD, 20));
mChartTheme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 15)); //标题
mChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15));
ChartFactory.setChartTheme(mChartTheme);
chart = ChartFactory.createPieChart("图书销量统计图", // 图表标题
data, // 数据
true, // 是不是显示图例
false, // 是不是显示工具提示
false // 是不是生成URL
);
//设置1系列的属性
//取得饼图的Plot对象
PiePlot plot = (PiePlot)chart.getPlot();
//用来显示标注的注解,{0}:{1}用来设置显示的格式
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}"));
plot.setBackgroundPaint(Color.gray);//设置背风景
//设置简单标签
plot.setSimpleLabels(true);
//标题
TextTitle texttitle=chart.getTitle();
texttitle.setFont(new Font("宋体", Font.BOLD, 30));
//图示
LegendTitle legendtitle =chart.getLegend();
legendtitle.setItemFont(new Font("宋体", Font.BOLD, 14));
//设定背景透明度(0⑴.0之间)
plot.setBackgroundAlpha(0.5f);
//设定前景透明度(0⑴.0之间)
plot.setForegroundAlpha(0.60f);
}
private PieDataset createDataset() {
double[][] table = null;
String[] name = null;
String[] number = null;
int result = 0;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sale", "root", "fab");
ResultSet rs = conn.createStatement().executeQuery("select name,number from sale");
// 获得行数
if (rs.last()){
result = rs.getRow();
rs.beforeFirst(); // 指针回滚
}
table = new double[result][rs.getMetaData().getColumnCount() - 1];// 定义寄存数据的2维数组
name = new String[result];
number = new String[rs.getMetaData().getColumnCount() - 1]; // 定义寄存数据表头的1维数组
rs.next();
for (int j = 0; j < rs.getMetaData().getColumnCount() - 1; j++) {
number[j] = rs.getMetaData().getColumnName(j + 2); // 取出表头并寄存数组
}
int i = 0;
rs.beforeFirst();
while (rs.next()) {
name[i] = rs.getString(1);
for (int j = 0; j < rs.getMetaData().getColumnCount() - 1; j++)
table[i][j] = rs.getDouble(j + 2); // 取出数据并存入2维数组
i++;
}
conn.close(); // 关闭连接
rs.close(); // 关闭查询
} catch (Exception ex) {
System.err.println("Exception:" + ex.getMessage());
}
//创建DefaultPieDataset类型的数据集,并行数据集中添加数据(从数据库中取的数据)
DefaultPieDataset dataset = new DefaultPieDataset();
for (int i = 0; i < number.length; i++)
for (int j = 0; j < result; j++) {
dataset.setValue(name[j],table[j][i] );
//调试用
System.out.println(table[j][i]);
System.out.println(name[j]);
}
return dataset;
}
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
/*
SQLyog 企业版 - MySQL GUI v7.14
MySQL - 5.0.18-nt : Database - sale
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`sale` /*!40100 DEFAULT CHARACTER SET gbk */;
USE `sale`;
/*Table structure for table `sale` */
DROP TABLE IF EXISTS `sale`;
CREATE TABLE `sale` (
`name` varchar(150) default NULL COMMENT '书名',
`number` varchar(150) default NULL COMMENT '数量'
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*Data for the table `sale` */
insert into `sale`(`name`,`number`) values ('C++','20'),('Java','20'),('数据结构','30'),('安卓','40'),('IOS','25');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
8.通过http://localhost:8080/JavafreeChartReport/要求访问,就会出现以下图3所示:
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠