2010.03.10——JfreeChart与后台交互之饼图
[b]这个例子所能达到的目的:
从后台去数据,生成对应的饼图,并显示在页面上[/b]
[color=green]**************************************************
web.xml
**************************************************[/color]
[color=green]**************************************************
spring.xml
**************************************************[/color]
[color=green]**************************************************
pojo类
**************************************************[/color]
[color=green]******************TuDi.java[/color]
[color=green]**************************************************
TestDaoImp
**************************************************[/color]
[color=green]**************************************************
TestServiceImp
**************************************************[/color]
[color=green]**************************************************
TestControl
**************************************************[/color]
[color=green]
**************************************************
柱状图:
**************************************************[/color]
[color=blue]这个,和原来的饼图 就两点区别:
1.dataset要改,改为从数据库中获取,我已经去掉了
2.就是drawToHtml(),这个方法的
ChartUtilities.writeImageMap(out, fileName, info, false);
out.flush();
这两句话要注释
因为我们现在只需要生成图片的地址就行了 不需要立马就放到页面上去[/color]
[color=green]**************************************************
jsp
**************************************************[/color]
对了 还有数据库
[color=green]**************************************************
sql
**************************************************[/color]饼状图:
[b]这个例子所能达到的目的:
从后台去数据,生成对应的饼图,并显示在页面上[/b]
[color=green]**************************************************
web.xml
**************************************************[/color]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-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>/servlet/DisplayChart</url-pattern>
</servlet-mapping>
</web-app>
[color=green]**************************************************
spring.xml
**************************************************[/color]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">
<!--
<aop:aspectj-autoproxy proxy-target-class="true"/>
-->
<!-- 数据库外部文件配置 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list><value>classpath:db.properties</value></list>
</property>
<property name="fileEncoding" value="utf-8" />
</bean>
<!-- 数据库外部文件配置 -->
<!-- 配置数据源 使用dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置数据源 使用dbcp数据源 -->
<!-- Hibernate SessionFactory配置 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>pojo.TuDi</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
</props>
</property>
</bean>
<!-- Hibernate SessionFactory配置 -->
<!-- hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- hibernateTemplate -->
<!-- dao -->
<bean id="testDao" class="dao.TestDaoImp" >
<property name="hibernateTemplate">
<ref bean="hibernateTemplate" />
</property>
</bean>
<!-- dao -->
<!-- serice -->
<bean id="testService" class="service.TestServiceImp" >
<property name="testDao" >
<ref bean="testDao" />
</property>
</bean>
<!-- serice -->
<!-- spring MVC -->
<bean id="testDelegate" class="control.TestControl">
<property name="testService"><ref bean="testService"/></property>
</bean>
<bean id="testController" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
<property name="methodNameResolver" ref="propMethodNameResolver"/>
<property name="delegate" ref="testDelegate"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/test_*.do">testController</prop>
</props>
</property>
</bean>
<bean id="propMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name="mappings">
<props>
<prop key="/test_2.do">test2</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="prefix"><value></value></property>
<property name="suffix"><value>.jsp</value></property>
<property name="contentType"><value>text/html;charset=utf-8</value></property>
</bean>
<!-- spring MVC -->
</beans>
[color=green]**************************************************
pojo类
**************************************************[/color]
[color=green]******************TuDi.java[/color]
package pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="TUDI")
public class TuDi {
private String name;
@Id
private Integer value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
[color=green]**************************************************
TestDaoImp
**************************************************[/color]
package dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import pojo.TuDi;
public class TestDaoImp extends HibernateDaoSupport implements TestDao {
public List<TuDi> query3(){
String hql = "from TuDi";
return (List<TuDi>)this.getHibernateTemplate().find(hql);
}
}
[color=green]**************************************************
TestServiceImp
**************************************************[/color]
package service;
import java.util.List;
import pojo.TuDi;
import dao.TestDao;
public class TestServiceImp implements TestService {
private TestDao testDao;
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
public List<TuDi> query3(){
return this.testDao.query3();
}
}
[color=green]**************************************************
TestControl
**************************************************[/color]
package control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.web.servlet.ModelAndView;
import pojo.PieChartTest;
import pojo.TuDi;
import service.TestService;
public class TestControl {
private TestService testService;
public TestService getTestService() {
return testService;
}
public void setTestService(TestService testService) {
this.testService = testService;
}
public ModelAndView test2(HttpServletRequest request,HttpServletResponse response) throws IOException{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
List<TuDi> list = this.testService.query3();
DefaultPieDataset dataset = new DefaultPieDataset();
for(TuDi o : list){
dataset.setValue(o.getName(), o.getValue());
}
PrintWriter out = response.getWriter();
String str = PieChartTest.drawToHtml(PieChartTest.createChart(dataset), request.getSession(), out);
request.setAttribute("data", str);
ModelAndView mav = new ModelAndView("pieChart2");
return mav;
}
}
[color=green]
**************************************************
柱状图:
**************************************************[/color]
package pojo;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
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.TextTitle;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
/**
* 使用JFreeChart绘制饼图
* @author qiujy
*/
public class PieChartTest {
/**
* step1:创建数据集对象
* @return
*/
public static PieDataset createDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("java程序设计语言", 10000);
dataset.setValue("JSP基础与案例开发详解", 20000);
dataset.setValue("struts基础与案例开发详解", 30000);
dataset.setValue("精通JSF", 40000);
return dataset;
}
/**
* step2:创建图表
* @param dataset
* @return
*/
public static JFreeChart createChart(PieDataset dataset) {
JFreeChart chart = ChartFactory.createPieChart3D(
//JFreeChart chart = ChartFactory.createPieChart(
"原创图书销量统计", // 图表标题
dataset, // 数据集
true, // 是否显示图例
true, // 是否显示工具提示
false // 是否生成URL
);
//设置标题字体==为了防止中文乱码:必须设置字体
chart.setTitle(new TextTitle("原创图书销量统计", new Font("黑体", Font.ITALIC, 22)));
//设置图例的字体==为了防止中文乱码:必须设置字体
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 12));
// 获取饼图的Plot对象(实际图表)
PiePlot plot = (PiePlot) chart.getPlot();
//图形边框颜色
plot.setBaseSectionOutlinePaint(Color.GRAY);
//图形边框粗细
plot.setBaseSectionOutlineStroke(new BasicStroke(0.0f));
//设置饼状图的绘制方向,可以按顺时针方向绘制,也可以按逆时针方向绘制
plot.setDirection(Rotation.ANTICLOCKWISE);
//设置绘制角度(图形旋转角度)
plot.setStartAngle(50);
//设置突出显示的数据块
plot.setExplodePercent("One", 0.1D);
//设置背景色透明度
plot.setBackgroundAlpha(0.7F);
// 设置前景色透明度
plot.setForegroundAlpha(0.65F);
//设置区块标签的字体==为了防止中文乱码:必须设置字体
plot.setLabelFont(new Font("隶书", Font.PLAIN, 12));
// 扇区分离显示,对3D图不起效
plot.setExplodePercent(dataset.getKey(3), 0.1D);
// 图例显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}:{1}\r\n({2})", NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
// 图例显示百分比
// plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
// 指定显示的饼图为:圆形(true) 还是椭圆形(false)
plot.setCircular(false);
// 没有数据的时候显示的内容
plot.setNoDataMessage("找不到可用数据...");
//设置鼠标悬停提示
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
//设置热点链接
//plot.setURLGenerator(new StandardPieURLGenerator("detail.jsp"));
return chart;
}
/**
* step3: 输出图表到网页
* @param destPath
* @param chart
*/
public static String drawToHtml(JFreeChart chart,HttpSession session,PrintWriter out){
ChartRenderingInfo info = new ChartRenderingInfo(
new StandardEntityCollection());
String fileName = "";
try
{
fileName = ServletUtilities.saveChartAsPNG(chart, 500, 300, info,
session);//生成图片
// Write the image map to the PrintWriter
//ChartUtilities.writeImageMap(out, fileName, info, false);
}
catch (IOException e)
{
e.printStackTrace();
}
//out.flush();
return fileName;//返回生成图片的文件名
}
}
[color=blue]这个,和原来的饼图 就两点区别:
1.dataset要改,改为从数据库中获取,我已经去掉了
2.就是drawToHtml(),这个方法的
ChartUtilities.writeImageMap(out, fileName, info, false);
out.flush();
这两句话要注释
因为我们现在只需要生成图片的地址就行了 不需要立马就放到页面上去[/color]
[color=green]**************************************************
jsp
**************************************************[/color]
<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@page isELIgnored="false" %>
<html>
<head>
<title> JFreeChart使用例子</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
</head>
<body>
<img src="servlet/DisplayChart?filename=${data }" id="p" width="500" height="300" border="0">
</body>
</html>
对了 还有数据库
[color=green]**************************************************
sql
**************************************************[/color]饼状图:
create table tudi(
name varchar2(20),
value number(20)
)
;
insert into tudi values('工业用房',2000);
insert into tudi values('其他',1500);
insert into tudi values('教育用房',3200);
insert into tudi values('办公用房',7500);
insert into tudi values('小区配套公寓',4100);
insert into tudi values('住宅',13000);