下载Jfreechart,引入jar包
![](http://static.oschina.net/uploads/space/2013/0325/220419_xoKY_154489.jpg)
PieChartServlet.java
public class PieChartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/png; charset=utf-8");
//获取数据集对象
PieDataset dataset = createPieDataset();
String language = "The 13 years programming language list";
//创建图形对象
JFreeChart jfreechart = ChartFactory
.createPieChart3D(language, dataset, true, true, false);
//获得图表区域对象
PiePlot pieplot = (PiePlot)jfreechart.getPlot();
//设置图标区域的标签字体
pieplot.setLabelFont(new Font("宋体", 0, 12));
//设置图标区域无数据时默认显示的文字
pieplot.setNoDataMessage("没有排行数据");
pieplot.setCircular(false);
pieplot.setLabelGap(0.02D);
//将图表以数据流的方式返回给客户端
ChartUtilities.writeChartAsPNG(response.getOutputStream(),
jfreechart, 500, 270);
}
/**
* 返回数据集
* @return
*/
public PieDataset createPieDataset() {
//创建饼形图数据对象
DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
defaultpiedataset.setValue("JAVA", DataUtils.getRandomData());
defaultpiedataset.setValue("JavaScript", DataUtils.getRandomData());
defaultpiedataset.setValue("Perl", DataUtils.getRandomData());
defaultpiedataset.setValue("Python", DataUtils.getRandomData());
defaultpiedataset.setValue("C/C++", DataUtils.getRandomData());
return defaultpiedataset;
}
}
DataUtils.java
public class DataUtils {
private static Random random = new Random();
private static final int MAX_NUMBER = 100;
/**
* 取0~100之间的数
*/
public static int getRandomData() {
return random.nextInt(MAX_NUMBER);
}
}
页面:
![](http://static.oschina.net/uploads/space/2013/0325/220703_cDwA_154489.jpg)
Jfreechart还提供了对多种图形的支持。