1.在myeclipse中创建Webproject工程,本工程名为:JavafreeChartReport
2.所需要的jar包如下图所示
3.工程目录的格式如下图所示
4.新建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>
<constant name="struts.action.extension" value="do,action"/>
<package name="pie" extends="struts-default" namespace="/pie">
<action name="piechart" class="com.lyf.jf.PieChartAction" method="getChart">
<result name="pie">../pie.jsp</result>
</action>
</package>
<package name="bar" namespace="/pie" extends="jfreechart-default">
<action name="barchart" class="com.lyf.jf.BarChartAction" >
<result type="chart">
<param name="width">700</param>
<param name="height">400</param>
</result>
</action>
</package>
</struts>
5.修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<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>
<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/servletDisplayChart</url-pattern>
</servlet-mapping>
</web-app>
6.新建pie.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<P ALIGN="CENTER">
<s:property value="mapMessage" escape="false"/>
<img src="<s:property value=‘src‘/>" border=0 usemap="#map0">
</P>
7.新建类PieChartAction
package com.lyf.jf;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.DefaultPieDataset;
public class PieChartAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
static final long serialVersionUID = 0L;
private HttpServletRequest request;
private HttpServletResponse response;
private String mapMessage;
private String src;
public String getChart() throws IOException {
//生成饼图
JFreeChart chart = ChartFactory.createPieChart(
"图书销售统计表", //图表标题
getDateSet(), //数据
true, //是否显示图例
true, //是否显示工具提示
true //是否生成URL
);
//设置标题及标题字体
chart.setTitle(new TextTitle("图书销售统计图",new Font("黑体",Font.ITALIC,22)));
//建一个图例
LegendTitle legendTitle = chart.getLegend(0);
//设置图例字体
legendTitle.setItemFont(new Font("宋体",Font.BOLD,14));
//获取饼图plot对象
PiePlot plot = (PiePlot) chart.getPlot();
//用来显示标注的注解,{0}:{1}用来设置显示的格式
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}"));
plot.setBackgroundPaint(Color.gray);//设置背景色
//设置简单标签
plot.setSimpleLabels(true);
//设置plot字体
plot.setLabelFont(new Font("宋体",Font.BOLD,18));
//设置背景透明度(0~1)
plot.setBackgroundAlpha(0.9f);
//-------------------热点设置----------------------------//
//设定链接
plot.setNoDataMessage("No data available");
String str =request.getContextPath()+"/pie/barchart.action";
plot.setURLGenerator(new StandardPieURLGenerator(str,"type"));
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
StandardEntityCollection sec = new StandardEntityCollection();
//生成RenderingInfo实例,info参数就是图片的热点信息
ChartRenderingInfo info = new ChartRenderingInfo(sec);
response.setCharacterEncoding("GBK");
String filename = null;
try {
filename = ServletUtilities.saveChartAsJPEG(chart, 700, 500, info, request.getSession());
} catch (IOException e) {
e.printStackTrace();
}
mapMessage = ChartUtilities.getImageMap("map0", info);
src = request.getContextPath()+"/servletDisplayChart?filename=" + filename;
return "pie";
}
private static DefaultPieDataset getDateSet() {
//提供生成饼图的数据
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/bss", "root", "fab");
ResultSet rs = conn.createStatement().executeQuery("select bookname,booknumber from book");
// 取得行数
if (rs.last()){
result = rs.getRow();
rs.beforeFirst(); // 指针回滚
}
table = new double[result][rs.getMetaData().getColumnCount() - 1];// 定义存放数据的二维数组
name = new String[result];
number = new String[rs.getMetaData().getColumnCount() - 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); // 取出数据并存入二维数组
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 void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public String getMapMessage() {
return mapMessage;
}
public void setMapMessage(String mapMessage) {
this.mapMessage = mapMessage;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
8.新建BarChartAction类
package com.lyf.jf;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
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.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChartAction extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
static final long serialVersionUID = 0L;
public JFreeChart getChart() throws IOException {
//---------------------逻辑判断分割线-------------------------------
CategoryDataset dataset;
String queryString = request.getQueryString();
queryString = java.net.URLDecoder.decode(queryString , "UTF-8");
System.out.println(queryString);
String type = null;
for(String param : queryString.split("&"))
{
String[] nameValue = param.split("=");
type = nameValue[0].equals("type") ? nameValue[1] : type;
}
String subTitle = "";
if(type.equals("JAVA教程"))
{
dataset = getDateSet1();
subTitle="JAVA教程";
}
else if(type.equals("c++教程"))
{
dataset = getDateSet4();
subTitle="c++教程";
}
else if(type.equals("C#教程"))
{
dataset = getDateSet2();
subTitle="C#教程";
}
else
{
dataset = getDateSet3();
subTitle="VC++教程";
}
//生成柱状图
JFreeChart chart = ChartFactory.createBarChart (
"图书销售统计表", //图表标题
"月份", //目录轴的显示标签
"销量", //数值轴的显示标签
dataset, //数据
//PlotOrientation.HORIZONTAL, //图表方向水平
PlotOrientation.VERTICAL, //图表方向垂直
false, //是否显示图例
false, //是否显示工具提示
false //是否生成URL
);
//设置标题及标题字体
chart.setTitle(new TextTitle("<<"+subTitle+">>销售统计图",new Font("黑体",Font.ITALIC,22)));
//获取柱状图plot对象
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//设置柱型的颜色
plot.getRenderer().setSeriesPaint(0, Color.blue);
//取得横轴
CategoryAxis categoryAxis = plot.getDomainAxis();
//设置横轴的字体
categoryAxis.setLabelFont(new Font("宋体",Font.BOLD,22));
//设置分类标签以45度倾斜
categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
//设置分类标签字体
categoryAxis.setTickLabelFont(new Font("宋体",Font.BOLD,22));
//取得纵轴
NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
//设置纵轴的字体
numberAxis.setLabelFont(new Font("宋体",Font.BOLD,22));
//设置背景透明度(0~1)
plot.setBackgroundAlpha(0.9f);
return chart;
}
//------------------------提供数据分割线--------------------
private static DefaultCategoryDataset getDateSet4() {
System.out.println("c++");
//提供生成柱形图的数据
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(47,"c++教程", "06年10月");
dataset.addValue(60,"c++教程", "06年11月");
dataset.addValue(20,"c++教程","06年12月" );
dataset.addValue(50,"c++教程","07年1月");
return dataset;
}
private static DefaultCategoryDataset getDateSet1() {
System.out.println("java");
//提供生成柱形图的数据
DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
dataset1.addValue(9,"JAVA教程", "06年10月");
dataset1.addValue(10,"JAVA教程", "06年11月");
dataset1.addValue(20,"JAVA教程", "06年12月" );
dataset1.addValue(10,"JAVA教程", "07年1月");
return dataset1;
}
private static DefaultCategoryDataset getDateSet2() {
System.out.println("C#");
//提供生成柱形图的数据
DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
dataset2.addValue(27,"C#教程", "06年10月");
dataset2.addValue(23,"C#教程", "06年11月");
dataset2.addValue(40,"C#教程","06年12月" );
dataset2.addValue(70,"C#教程", "07年1月");
return dataset2;
}
private static DefaultCategoryDataset getDateSet3() {
System.out.println("VC++");
//提供生成柱形图的数据
DefaultCategoryDataset dataset3 = new DefaultCategoryDataset();
dataset3.addValue(48,"VC++教程", "06年10月");
dataset3.addValue(63,"VC++教程", "06年11月");
dataset3.addValue(29,"VC++教程","06年12月" );
dataset3.addValue(49,"VC++教程","07年1月");
return dataset3;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
10.数据库脚本:
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=‘‘*/;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`bss` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `bss`;
/*Table structure for table `book` */
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`bookname` varchar(150) default NULL,
`booknumber` varchar(150) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `book` */
insert into `book`(`bookname`,`booknumber`) values (‘JAVA教程‘,‘30‘),(‘C++教程‘,‘23‘),(‘C#教程‘,‘20‘),(‘VC++教程‘,‘15‘);
/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
11.将工程部署到Tomcat中
12.通过http://localhost:8080/JavafreeChartReport/pie/piechart.action请求访问,就会出现如下图示:
12.点击热点区域即可看到对应的柱状图如下图所示