jfreechart之在swt和jsp页面绘制饼图、柱状图、时间序列图

   嗯 先提供几个关于jfreechart的api和开发者手册的文档

   官网jfreechart的api http://www.jfree.org/jfreechart/api/javadoc/index.html  网页版的

   jfreechart的chm版的api  http://download.csdn.net/detail/undergrowth/6217365

 jreechart的开发者手册1.0.13版的   http://download.csdn.net/detail/undergrowth/6217387

还有一个 包含jfreechart的文档,jcommon等等之类的     http://sourceforge.net/projects/jfreechart/files/

    先来看看swt版的饼图、柱状图、时间序列图

  其实使用jfreechart来进行绘图,无论是什么图,都有三个步骤:

1.显示什么(即数据源)

2.谁来显示(即谁来负责将数据转换为图片)

3.在哪里显示(即是在jsp/servlet/swt/applet中的哪里显示)


先来看看饼图,因为所有的操作在代码里面都加了详细的注释,所以这里就不解释了,看源代码和效果图即可

package com.undergrowth;

import java.awt.Color;
import java.awt.Font;
import java.text.NumberFormat;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
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;

public class JFreeChartSwtPie {

	/**
	 * @param args
	 * 1.显示什么----数据集
	 * 2.谁来显示----JFreeChart/ChartFactory
	 * 3.在哪里显示---ChartFrame/Servlet
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1.显示什么
		//以键值对的方式进行存储数据
		DefaultPieDataset dataset=new DefaultPieDataset();
		dataset.setValue("初级程序员", 600);
		dataset.setValue("中级程序员", 200);
		dataset.setValue("高级程序员", 100);
		dataset.setValue("其他", 100);
		//2.谁来显示
		JFreeChart chart=ChartFactory.createPieChart("IT从业人员", dataset, true, true, false);
		//因为中文显示的问题 自定义Font 解决中文乱码问题
		//JFreeChart负责将Title对象,Legend对象,Plot对象,Dataset对象组合起来绘制图表
		Font fontTitleFont=new Font("隶书", Font.BOLD, 20);
		Font fontLegendFont=new Font("隶书", Font.BOLD, 10);
		Font fontLabelFont=new Font("隶书", Font.BOLD, 14);
		//修改图表标题Title的字体
		TextTitle title=chart.getTitle();
		title.setFont(fontTitleFont);
		//修改图表图例Legend的字体
		LegendTitle legendTitle=chart.getLegend();
		legendTitle.setItemFont(fontLegendFont);
		//修改图表绘制Plot字体
		PiePlot piePlot=(PiePlot) chart.getPlot();
		piePlot.setLabelFont(fontLabelFont);
		//修改显示区域其他的填充颜色 默认为黄色 现在修改为灰色
		 piePlot.setSectionPaint("其他",Color.gray);
		 //修改区域其他轮廓的颜色为白色
		 piePlot.setSectionOutlinePaint("其他", Color.white);
		 //关闭区域轮廓
		 //piePlot.setSectionOutlinesVisible(false);
		 //当数据集中有0值或者null时,忽略 负值的话默认是忽略的
		 piePlot.setIgnoreNullValues(true);
		 piePlot.setIgnoreZeroValues(true);
		 //用于修改区域标签的显示格式 key=value(百分数)
		 PieSectionLabelGenerator generator=new StandardPieSectionLabelGenerator("{0}={1}({2})",NumberFormat.getInstance(),NumberFormat.getPercentInstance());
		 piePlot.setLabelGenerator(generator);
		 //修改图例区域的显示效果格式  key(人)
		 PieSectionLabelGenerator generator2=new StandardPieSectionLabelGenerator("{0}(人)");
		 piePlot.setLegendLabelGenerator(generator2);
		 //设置某一块(其他)区域分离出来的效果 后面的0.3数字表示其他区域偏离半径长度的百分比
		 piePlot.setExplodePercent("其他", 0.3);
		 
		//3.在哪显示
		//使用ChartFrame 继承JFrame
		ChartFrame frame=new ChartFrame("IT", chart);
		frame.pack();//调整大小到合适位置
		frame.setVisible(true);
		
	}

}

效果图:



柱状图:

package com.undergrowth;

import java.awt.Color;
import java.awt.Font;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
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.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RefineryUtilities;

public class JFreeChartSwtBar{

	

	/**
	 * @param args
	 * 1.显示什么
	 * 2.谁来显示
	 * 3.在哪显示
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1.显示什么
		//DefaultCategoryDataset显示表格数据  以列进行分组 以行进行着色
		DefaultCategoryDataset dataset=new DefaultCategoryDataset();
		//第一行
		dataset.setValue(144, "Google", "总收入");
		dataset.setValue(70, "Google", "盈利");
		dataset.setValue(2467, "Google", "市值");
		//第二行
		dataset.setValue(100, "baidu", "总收入");
		dataset.setValue(50, "baidu", "盈利");
		dataset.setValue(517, "baidu", "市值");
		//第三行
		dataset.setValue(110, "tecent", "总收入");
		dataset.setValue(60, "tecent", "盈利");
		dataset.setValue(650, "tecent", "市值");
		//第四行
		dataset.setValue(130, "阿里巴巴", "总收入");
		dataset.setValue(80, "阿里巴巴", "盈利");
		dataset.setValue(1000, "阿里巴巴", "市值");
		
		//2.谁来显示
		JFreeChart chart=ChartFactory.createBarChart("各大公司收入/市值比较", "各大公司", "单位(亿/美元)", dataset, PlotOrientation.VERTICAL, true, true, false);
		//设置图表背景为白色
		chart.setBackgroundPaint(Color.white);
		//因为中文显示的问题 自定义Font 解决中文乱码问题
				//JFreeChart负责将Title对象,Legend对象,Plot对象,Dataset对象组合起来绘制图表
				Font fontTitleFont=new Font("隶书", Font.BOLD, 20);
				Font fontLegendFont=new Font("隶书", Font.BOLD, 10);
				Font fontLabelFont=new Font("隶书", Font.BOLD, 14);
				//修改图表标题Title的字体
				TextTitle title=chart.getTitle();
				title.setFont(fontTitleFont);
				//修改图表图例Legend的字体
				LegendTitle legendTitle=chart.getLegend();
				legendTitle.setItemFont(fontLegendFont);
				//修改图表绘制Plot字体
				//CategoryPlot用于管理坐标轴(CategoryAxis,ValueAxis),数据集(Dataset),渲染器(BarRender),
				CategoryPlot plot=chart.getCategoryPlot();
				//设置plot的背景为灰色 网格线为白色
				plot.setBackgroundPaint(Color.lightGray);
				plot.setRangeGridlinePaint(Color.white);
				//修改同一组间每一项的间距为0
				BarRenderer renderer=(BarRenderer) plot.getRenderer();
				//renderer.setItemMargin(0);
				//设置每一项上显示数字
				renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
				renderer.setBaseItemLabelsVisible(true);
				//水平方向
				CategoryAxis categoryAxis=plot.getDomainAxis();
				categoryAxis.setLabelFont(fontLabelFont);
				 categoryAxis.setTickLabelFont(fontLabelFont); //设置每一个标记的字体(即每一列的列名)
				//垂直方向
				ValueAxis valueAxis=plot.getRangeAxis();
				valueAxis.setLabelFont(fontLabelFont);
		
		//3.在哪显示
		ChartFrame frame=new ChartFrame("各大公司收入/市值比较", chart);
		frame.pack(); //自动调整大小到合适
		RefineryUtilities.centerFrameOnScreen(frame); //设置位于屏幕中央
		frame.setVisible(true);
	}

}

效果图:




时间序列图:

package com.undergrowth;

import java.awt.Font;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RefineryUtilities;

public class JFreeChartSwtTimeSerisl {

	/**
	 * @param args
	 *1.显示什么
	 *2.谁来显示
	 *3.在哪显示
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
		// TODO Auto-generated method stub
		//1.显示什么
		
		TimeSeries s1=new TimeSeries("销售额", Month.class);
		s1.add(new Month(1,2013), 200);
		s1.add(new Month(2,2013), 200);
		s1.add(new Month(3,2013), 300);
		s1.add(new Month(4,2013),400);
		s1.add(new Month(5,2013), 200);
		s1.add(new Month(6,2013), 500);
		TimeSeries s2=new TimeSeries("盈利额",Month.class);
		s2.add(new Month(1,2013), 100);
		s2.add(new Month(2,2013), 80);
		s2.add(new Month(3,2013), 150);
		s2.add(new Month(4,2013),200);
		s2.add(new Month(5,2013), 600);
		s2.add(new Month(6,2013), 300);
		
		TimeSeriesCollection dataset=new TimeSeriesCollection();
		dataset.addSeries(s1);
		dataset.addSeries(s2);
		
		//2.谁来显示
		JFreeChart chart=ChartFactory.createTimeSeriesChart("乐麦德销售情况", "月份", "单位:(万元)", dataset, true, true, false);
		//因为中文显示的问题 自定义Font 解决中文乱码问题
		//JFreeChart负责将Title对象,Legend对象,Plot对象,Dataset对象组合起来绘制图表
		Font fontTitleFont=new Font("隶书", Font.BOLD, 20);
		Font fontLegendFont=new Font("隶书", Font.BOLD, 10);
		Font fontLabelFont=new Font("隶书", Font.BOLD, 14);
		//修改图表标题Title的字体
		TextTitle title=chart.getTitle();
		title.setFont(fontTitleFont);
		//修改图表图例Legend的字体
		LegendTitle legendTitle=chart.getLegend();
		legendTitle.setItemFont(fontLegendFont);
		//修改图标的绘制Plot
		XYPlot plot=chart.getXYPlot();
		//修改水平
		DateAxis domainAxis=(DateAxis) plot.getDomainAxis();
		domainAxis.setLabelFont(fontLabelFont);
		domainAxis.setTickLabelFont(fontLabelFont);
		//修改显示的日期格式
		domainAxis.setDateFormatOverride(new SimpleDateFormat("MM月"));
		domainAxis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1));
		//在每一个点上显示数据
		XYItemRenderer renderer=plot.getRenderer();
		renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
		renderer.setBaseItemLabelsVisible(true);
		//设置水平轴的显示日期范围
		domainAxis.setRange(new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-16"), new SimpleDateFormat("yyyy-MM-dd").parse("2013-6-31"));
		//修改垂直的
		ValueAxis rangeAxis=plot.getRangeAxis();
		rangeAxis.setLabelFont(fontLabelFont);
		rangeAxis.setRange(0, 650);
		
		//3.显示在哪
		ChartFrame frame=new ChartFrame("乐麦德2013年上半年销售情况", chart);
		frame.pack();
		RefineryUtilities.centerFrameOnScreen(frame);
		frame.setVisible(true);
	}

}

效果图:



      上面即是在swt上显示图片,其实在jsp页面上,没有太大的区别,只是三步中的最后一步换了而已,jsp页面的代码就没有加注释了,因为和上面的代码是差不多的,只是最后一步换掉而已.

    对于在jsp页面显示图片,需在在web.xml中添加如下配置信息:

<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>/DisplayChart</url-pattern>
</servlet-mapping> 
      添加它的目的是利用DisplayChart(继承HttpServlet)这个类来显示在临时目录中生成的图片,当然你也可以自己写一个servlet,来向输出流中输出你产生的图片,效果是一样的,不过就要用到ChartUtilities.writeChartAsPNG方法了

public static void writeChartAsPNG(java.io.OutputStream out,
                                   JFreeChart chart,
                                   int width,
                                   int height)
                            throws java.io.IOExceptionWrites a chart to an output stream in PNG format


我采用的是在web.xml中进行配置,输出而已

    jsp页面:

   饼图:

<%@page import="java.text.NumberFormat"%>
<%@page import="org.jfree.chart.labels.StandardPieSectionLabelGenerator"%>
<%@page import="org.jfree.chart.plot.PiePlot"%>
<%@page import="java.awt.Font"%>
<%@page import="org.jfree.data.general.DefaultPieDataset"%>
<%@page import="org.jfree.chart.ChartFactory"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	Font font=new Font("隶书",Font.BOLD,20);
	DefaultPieDataset dataset=new DefaultPieDataset();
	 dataset.setValue("美工", 200);
	dataset.setValue("中级程序员", 700);
	dataset.setValue("高级程序员", 700);
	dataset.setValue("其他", 1000); 
	JFreeChart chart=ChartFactory.createPieChart("IT行业职业分布图", dataset, true,false,false);
	PiePlot plot=(PiePlot)chart.getPlot();
	plot.setNoDataMessage("没有数据显示");
	StandardPieSectionLabelGenerator generator=new StandardPieSectionLabelGenerator("{0}:({1},{2})",NumberFormat.getNumberInstance(),NumberFormat.getPercentInstance());
	plot.setLabelFont(font);
	plot.setExplodePercent("其他", 0.1);
	plot.setLabelGenerator(generator);
    chart.getTitle().setFont(font);
    chart.getLegend().setItemFont(font);
	
	String filename=ServletUtilities.saveChartAsPNG(chart, 500, 300,null, session);
	String graphurl=request.getContextPath()+"/DisplayChart?filename="+filename;
%>
<center>
<img  src="<%=graphurl%>">
</center>
</body>
</html>

输入:http://localhost:8080/JFreeChart/pie.jsp

效果图:


柱状图:

<%@page import="org.jfree.ui.TextAnchor"%>
<%@page import="org.jfree.chart.labels.ItemLabelAnchor"%>
<%@page import="org.jfree.chart.labels.ItemLabelPosition"%>
<%@page import="org.jfree.chart.labels.StandardCategoryItemLabelGenerator"%>
<%@page import="org.jfree.chart.renderer.category.BarRenderer3D"%>
<%@page import="org.jfree.chart.axis.AxisLocation"%>
<%@page import="org.jfree.data.general.DatasetUtilities"%>
<%@page import="org.jfree.data.category.CategoryDataset"%>
<%@page import="org.jfree.chart.axis.ValueAxis"%>
<%@page import="org.jfree.chart.axis.CategoryAxis"%>
<%@page import="org.jfree.chart.plot.CategoryPlot"%>
<%@page import="java.awt.Color"%>
<%@page import="java.awt.Font"%>
<%@page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@page import="org.jfree.chart.plot.PlotOrientation"%>
<%@page import="org.jfree.chart.ChartFactory"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@page import="org.jfree.data.category.DefaultCategoryDataset"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<title>Insert title here</title>
</head>
<body>
<%
    Font font=new Font("隶书",Font.BOLD,20);
	String rows[]={"猪肉","牛肉","鸡肉"};
	String cols[]={"广州","株洲","上海"};
	double data[][]={{1000,1000,1000},{800,800,800},{600,600,600}};
	CategoryDataset dataset=DatasetUtilities.createCategoryDataset(rows, cols, data);
	
	JFreeChart chart=ChartFactory.createBarChart3D("肉类销售柱状图", "肉类", "销售", dataset, PlotOrientation.VERTICAL, true, true, false);
	chart.getTitle().setFont(font);  //设置标题的字体
	chart.setBackgroundPaint(Color.white); //绘制背景为白色
	CategoryPlot cpPlot=chart.getCategoryPlot();
	/* cpPlot.setDomainGridlinePaint(Color.black);
	cpPlot.setDomainGridlinesVisible(true);
	cpPlot.setRangeGridlinePaint(Color.red); */
	cpPlot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
	cpPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
	
	BarRenderer3D renderer=new BarRenderer3D();
	renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
	renderer.setBaseItemLabelsVisible(true);
	renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT));
	cpPlot.setRenderer(renderer);
	chart.getLegend().setItemFont(font);
	CategoryAxis ca=cpPlot.getDomainAxis();
	ca.setLabelFont(font);
	ca.setTickLabelFont(font);
	ValueAxis va=cpPlot.getRangeAxis();
	va.setLabelFont(font);
	
	
	String filename=ServletUtilities.saveChartAsPNG(chart, 500, 300,null, session);
	String graphurl=request.getContextPath()+"/DisplayChart?filename="+filename;
%>
<center>
<img  src="<%=graphurl%>">
</center>
</body>
</html>

输入:http://localhost:8080/JFreeChart/barchart4.jsp
效果图:


时间序列图:

<%@page import="org.jfree.chart.axis.DateTickUnitType"%>
<%@page import="org.jfree.chart.axis.DateTickUnit"%>
<%@page import="java.text.SimpleDateFormat,java.util.Date"%>
<%@page import="org.jfree.chart.axis.DateAxis"%>
<%@page import="org.jfree.chart.renderer.xy.XYLineAndShapeRenderer"%>
<%@page import="org.jfree.ui.TextAnchor"%>
<%@page import="org.jfree.chart.labels.ItemLabelAnchor"%>
<%@page import="org.jfree.chart.labels.ItemLabelPosition"%>
<%@page import="org.jfree.chart.labels.StandardXYItemLabelGenerator"%>
<%@page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>
<%@page import="org.jfree.chart.axis.ValueAxis"%>
<%@page import="org.jfree.chart.plot.XYPlot"%>
<%@page import="java.awt.Font"%>
<%@page import="org.jfree.chart.ChartFactory"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@page import="org.jfree.data.time.TimeSeriesCollection"%>
<%@page import="org.jfree.data.time.Month"%>
<%@page import="org.jfree.data.time.TimeSeries"%>
<%@page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		Font font=new Font("隶书",Font.BOLD,18);
		TimeSeries series=new TimeSeries("某网站的访问统计",Month.class);
		series.add(new Month(1,2013), 600);
		series.add(new Month(2,2013), 1100);
		series.add(new Month(3,2013), 800);
		series.add(new Month(4,2013), 900);
		series.add(new Month(5,2013), 400);
		series.add(new Month(6,2013), 700);
	    TimeSeriesCollection collection=new TimeSeriesCollection();
	    collection.addSeries(series);
	    JFreeChart chart=ChartFactory.createTimeSeriesChart("网站统计", "月份", "访问量", collection, true, true, true);
	    chart.getTitle().setFont(font);
	    chart.getLegend().setItemFont(font);
	    XYPlot plot=chart.getXYPlot();
	    
	    DateAxis dateAxis=(DateAxis)plot.getDomainAxis();
	    dateAxis.setDateFormatOverride(new SimpleDateFormat("M月"));
	    dateAxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1));
	    dateAxis.setRange(new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-16"), new SimpleDateFormat("yyyy-MM-dd").parse("2013-6-31"));
	    
	    ValueAxis valueAxis=plot.getDomainAxis();
	    valueAxis.setLabelFont(font);
	    valueAxis.setTickLabelFont(font);
	    
	    XYLineAndShapeRenderer linerRenderer=(XYLineAndShapeRenderer)plot.getRenderer();
	    linerRenderer.setBaseShapesVisible(true);
	    
	    XYItemRenderer renderer=plot.getRenderer();
	    renderer.setBaseItemLabelsVisible(true);
	    renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_CENTER));
	    renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
	    renderer.setBaseItemLabelFont(new Font("Dialog",1,12));
	    plot.setRenderer(renderer);
	    
	    ValueAxis valueAxis2=plot.getRangeAxis();
	    valueAxis2.setLabelFont(font);
		
	    String filename=ServletUtilities.saveChartAsPNG(chart, 600, 600,null, session);
		String graphurl=request.getContextPath()+"/DisplayChart?filename="+filename;
	%>
	<center>
	<img  src="<%=graphurl%>">
	</center>
</body>
</html>

输入:http://localhost:8080/JFreeChart/broken.jsp

效果图:


 

顺便加一个在jsp页面请求一个自定义的servlet显示图片(实质是想自定义的servlet的输出流中写入图片)

 getImage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String graphurl=request.getContextPath()+"/ServletTest";
out.println(graphurl);
%>
<img alt="jfreechart" src=<%=graphurl%>>
</body>
</html>


自定义的Servlet为ServletTest 代码如下:

package com.undergrowth;

import java.awt.Font;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 * Servlet implementation class ServletTest
 */
public class ServletTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		OutputStream outStr=response.getOutputStream();
		response.setContentType("image/png");
		//1.显示什么
		DefaultCategoryDataset dataset=new DefaultCategoryDataset();
		dataset.addValue(200, "系统分析师", "软件");
		dataset.addValue(100, "系统分析师", "硬件");
		//2.谁来显示
		Font fontLegend=new Font("隶书", Font.BOLD, 20);
		Font fontTitle=new Font("隶书", Font.BOLD, 30);
		Font font=new Font("隶书", Font.BOLD, 10);
		JFreeChart chart=ChartFactory.createBarChart3D("嵌入式开发人员统计", "分类", "人数", dataset, PlotOrientation.VERTICAL, true, true, false);
		chart.getLegend().setItemFont(fontLegend);
		chart.getTitle().setFont(fontTitle);
		chart.getCategoryPlot().getDomainAxis().setLabelFont(font);
		chart.getCategoryPlot().getDomainAxis().setTickLabelFont(font);
		chart.getCategoryPlot().getRangeAxis().setLabelFont(font);
		//3.在哪显示
		ChartUtilities.writeChartAsPNG(outStr, chart, 300, 300);
		//System.out.println("柱状图");
		outStr.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}


测试: http://localhost:8080/ServletTest/getImage.jsp

附:本文的源代码 http://download.csdn.net/detail/undergrowth/6217609

原文地址:https://www.cnblogs.com/liangxinzhi/p/4275604.html