2010.03.09(3)——JfreeChart与后台交互之柱状图
这个例子所能达到的目的:
[b]页面有几个复选框,当选择其中几个时,会生成对性的柱状图,并显示在页面上[/b]
[color=brown]**************************************************
web.xml
**************************************************[/color]
[color=brown]**************************************************
spring.xml
**************************************************[/color]
[color=brown]**************************************************
pojo类
**************************************************[/color]
[color=brown]******************LiangShi.java[/color]
[color=brown]*******************JianZhu.java[/color]
[color=brown]**************************************************
TestDao
**************************************************[/color]
[color=brown]**************************************************
TestService
**************************************************[/color]
[color=brown]**************************************************
TestControl
**************************************************[/color]
[color=brown]**************************************************
柱状图:
**************************************************[/color]
这个,和原来的柱状图 就两天区别:
[color=blue]1.dataset要改,改为从数据库中获取,我已经去掉了
2.就是drawToHtml(),这个方法的
ChartUtilities.writeImageMap(out, fileName, info, false);
out.flush();
这两句话要注释
因为我们现在只需要生成图片的地址就行了 不需要立马就放到页面上去[/color]
[color=brown]**************************************************
jsp
**************************************************[/color]
对了 还有数据库
[color=brown]**************************************************
sql
**************************************************[/color]
这个例子所能达到的目的:
[b]页面有几个复选框,当选择其中几个时,会生成对性的柱状图,并显示在页面上[/b]
[color=brown]**************************************************
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=brown]**************************************************
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.JianZhu</value>
<value>pojo.LiangShi</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_1.do">test</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=brown]**************************************************
pojo类
**************************************************[/color]
[color=brown]******************LiangShi.java[/color]
package pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="LIANGSHI")
public class LiangShi {
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=brown]*******************JianZhu.java[/color]
package pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="JIANZHU")
public class JianZhu {
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=brown]**************************************************
TestDao
**************************************************[/color]
package dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import pojo.JianZhu;
import pojo.LiangShi;
public class TestDaoImp extends HibernateDaoSupport implements TestDao {
public List<JianZhu> query1(){
String hql = "from JianZhu";
return (List<JianZhu>)this.getHibernateTemplate().find(hql);
}
public List<LiangShi> query2(){
String hql = "from LiangShi";
return (List<LiangShi>)this.getHibernateTemplate().find(hql);
}
public List<JianZhu> query1(Object[] values){
StringBuffer hql = new StringBuffer("from JianZhu o ");
if(values!=null){
hql.append("where ");
}
int i = 0;
for(Object o : values){
hql.append("o.name='").append(o).append("'");
i++;
if(i!=values.length)
hql.append(" or ");
}
System.out.println(hql.toString());
return (List<JianZhu>)this.getHibernateTemplate().find(hql.toString());
}
public List<LiangShi> query2(Object[] values){
StringBuffer hql = new StringBuffer("from LiangShi o ");
if(values!=null){
hql.append("where ");
}
int i = 0;
for(Object o : values){
hql.append("o.name='").append(o).append("'");
i++;
if(i!=values.length)
hql.append(" or ");
}
System.out.println(hql.toString());
return (List<LiangShi>)this.getHibernateTemplate().find(hql.toString());
}
}
[color=brown]**************************************************
TestService
**************************************************[/color]
package service;
import java.util.List;
import pojo.JianZhu;
import pojo.LiangShi;
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<JianZhu> query1(){
return this.testDao.query1();
}
public List<LiangShi> query2(){
return this.testDao.query2();
}
public List<JianZhu> query1(Object[] values) {
// TODO Auto-generated method stub
return this.testDao.query1(values);
}
public List<LiangShi> query2(Object[] values) {
// TODO Auto-generated method stub
return this.testDao.query2(values);
}
}
[color=brown]**************************************************
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.springframework.web.servlet.ModelAndView;
import pojo.BarChartTest;
import pojo.JianZhu;
import pojo.LiangShi;
import service.TestService;
public class TestControl {
private TestService testService;
public TestService getTestService() {
return testService;
}
public void setTestService(TestService testService) {
this.testService = testService;
}
public ModelAndView test(HttpServletRequest request,HttpServletResponse response) throws IOException{
String city = request.getParameter("city");
String type = request.getParameter("type");
String[] values1 = type.split("-");
String[] values = city.split("-");
List<JianZhu> list1 = null;
List<LiangShi> list2 = null;
for(String str : values1){
if(str.equals("jianzhu")){
list1 = testService.query1(values);
}
if(str.equals("liangshi")){
list2 = testService.query2(values);
}
}
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
if(list2!=null){
for(int i=0;i<list2.size();i++){
dataset.setValue(list2.get(i).getValue(), "粮食用地", list2.get(i).getName());
}
}
if(list1!=null){
for(int i=0;i<list1.size();i++){
dataset.setValue(list1.get(i).getValue(), "建筑用地", list1.get(i).getName());
}
}
PrintWriter out = response.getWriter();
String str = BarChartTest.drawToHtml(BarChartTest.createChart(dataset), request.getSession(), out;
out.print(str);
return null;
}
}
[color=brown]**************************************************
柱状图:
**************************************************[/color]
package pojo;
import java.awt.Color;
import java.awt.Font;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
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.axis.CategoryAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* 柱状图和折线图
* @author qiujy
*/
public class BarChartTest {
/**
* step2:创建图表
* @param dataset
* @return
*/
public static JFreeChart createChart(CategoryDataset dataset) {
JFreeChart chart = ChartFactory.createBarChart3D( //3D柱状图
//JFreeChart chart = ChartFactory.createLineChart3D( //3D折线图
"原创图书销量统计", //图表的标题
"图书名", //目录轴的显示标签
"销量", //数值轴的显示标签
dataset, //数据集
PlotOrientation.VERTICAL, //图表方式:V垂直;H水平
true, // 是否显示图例
false, // 是否显示工具提示
false // 是否生成URL
);
//===============为了防止中文乱码:必须设置字体
chart.setTitle(new TextTitle("原创图书销量统计", new Font("黑体", Font.ITALIC, 22)));
LegendTitle legend = chart.getLegend(); // 获取图例
legend.setItemFont(new Font("宋体", Font.BOLD, 12)); //设置图例的字体,防止中文乱码
CategoryPlot plot = (CategoryPlot) chart.getPlot(); // 获取柱图的Plot对象(实际图表)
// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
plot.setBackgroundPaint(new Color(255, 255, 204));
plot.setForegroundAlpha(0.65F); //设置前景色透明度
// 设置横虚线可见
plot.setRangeGridlinesVisible(true);
// 虚线色彩
plot.setRangeGridlinePaint(Color.gray);
CategoryAxis h = plot.getDomainAxis(); //获取x轴
h.setMaximumCategoryLabelWidthRatio(1.0f);// 横轴上的 Lable 是否完整显示
h.setLabelFont(new Font("宋体", Font.BOLD, 12));//设置字体,防止中文乱码
h.setTickLabelFont(new Font("宋体", Font.BOLD, 12));// 轴数值
//h.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//45度倾斜
plot.getRangeAxis().setLabelFont(new Font("宋体", Font.BOLD, 12)); //Y轴设置字体,防止中文乱码
//柱图的呈现器
BarRenderer3D renderer = new BarRenderer3D();
// 设置柱子宽度
//renderer.setMaximumBarWidth(0.05);
// 设置柱子高度
//renderer.setMinimumBarLength(0.2);
// 设置柱子边框颜色
renderer.setBaseOutlinePaint(Color.BLACK);
// 设置柱子边框可见
renderer.setDrawBarOutline(true);
//设置每个柱的颜色
renderer.setSeriesPaint(0, Color.BLUE);
renderer.setSeriesPaint(1, Color.GREEN);
renderer.setSeriesPaint(2, Color.RED);
//设置每个地区所包含的平行柱的之间距离
renderer.setItemMargin(0.05);
// 显示每个柱的数值,并修改该数值的字体属性
renderer.setIncludeBaseInRange(true);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
// 设置柱的透明度
plot.setForegroundAlpha(1.0f);
//给柱图添加呈现器
plot.setRenderer(renderer);
// 没有数据的时候显示的内容
plot.setNoDataMessage("找不到可用数据...");
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=brown]**************************************************
jsp
**************************************************[/color]
<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<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>
<script type="text/javascript">
$(function(){
$("#p").hide();
$("#bn").click(ajax);
})
function ajax(){
$.ajax({
type: "post",
url: "test_1.do",
data: {type:fn("t1"),city:fn("t2")},
dataType: "text",
success: function(data){
//$("#p").attr("usermap","#"+data);
$("#p").attr("src","servlet/DisplayChart?filename="+data);
$("#p").show();
}
});
}
function fn(id){
var str = "";
var i = 0;
$("#"+id+" :checkbox:checked").each(function(){
str += $(this).val();
i++;
if(i!=$("#"+id+" :checkbox:checked").length){
str += "-";
}
});
return str;
}
</script>
</head>
<body>
<div id="t1">
类型:
建筑<input type="checkbox" name="checkbox" id="checkbox1" value="jianzhu"/>
粮食<input type="checkbox" name="checkbox" id="checkbox2" value="liangshi"/><br />
</div>
<div id="t2">
地区:
唐家岭<input type="checkbox" name="checkbox" id="checkbox3" value="唐家岭"/>
东北旺<input type="checkbox" name="checkbox" id="checkbox4" value="东北旺"/>
上地<input type="checkbox" name="checkbox" id="checkbox5" value="上地"/><br />
</div>
<input type="button" value="生成图片" id="bn" /><br />
<img id="p" width="500" height="300" border="0" >
</body>
</html>
对了 还有数据库
[color=brown]**************************************************
sql
**************************************************[/color]
create table jianzhu(
name varchar2(20),
value number(20)
)
;
create table liangshi(
name varchar2(20),
value number(20)
)
;
insert into jianzhu values('唐家岭',2000);
insert into jianzhu values('东北旺',1500);
insert into jianzhu values('上地',3200);
insert into liangshi values('唐家岭',7500);
insert into liangshi values('东北旺',4100);
insert into liangshi values('上地',13000);