要导入两个jar包:jfreechart.jar jcommon.jar
Servlet:
package com.jxnu.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.servlet.ServletUtilities; import org.jfree.data.category.DefaultCategoryDataset; public class BarChartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;chartSet=UTF-8"); HttpSession session = request.getSession(); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(3, "", "优秀"); dataset.addValue(8, "", "良好"); dataset.addValue(15, "", "中等"); dataset.addValue(12, "", "及格"); dataset.addValue(8, "", "不及格"); JFreeChart chart = ChartFactory.createBarChart("考试成绩统计图", "成绩", "人数", dataset, PlotOrientation.HORIZONTAL, false, false, false); String filename = ServletUtilities.saveChartAsPNG(chart, 300, 200, session);//一般保存在Session范围内 String graphURL = "/Prj28/DisplayChart?filename=" + filename; //session.setAttribute("graphURL", graphURL);下面代码也能实现同样功能 request.setAttribute("graphURL", graphURL); request.getRequestDispatcher("/barChart1.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
JSP页面:
<%@ page language="java" pageEncoding="UTF-8"%> <html> <body> <img src="${requestScope.graphURL}" alt="图片不存在"/> </body> </html>
访问地址:http://127.0.0.1:8080/Prj28/servlet/BarChartServlet
用JFreeChart开发图片报表,码迷,mamicode.com
原文地址:http://blog.csdn.net/tangliuqing/article/details/24843599