Jfreechart学习笔记6-Servlet创建Jfreechart的方法

数据库的内容
CATEGORY | VALUE
---------+------
London   | 54.3
New York | 43.4
Paris    | 17.9


import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

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.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.jdbc.JDBCPieDataset;

public class PieServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			//获得输出流
			OutputStream os = response.getOutputStream();
			//获得相于的数据对象
			DefaultPieDataset dataset = (DefaultPieDataset) this.readData();
			
			JFreeChart chart = ChartFactory.createPieChart("Test", dataset, true, true, false);
				response.setContentType("image/png");
				//写到输出流,并在页面上面显示
				ChartUtilities.writeChartAsPNG(os, chart, 800, 600);
				os.close();
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	/**
	 *  连结JDBC,并创建JDBCPieDataset对象返回
	 * @return
	 */
	private PieDataset readData() {
		//创建JDBCPieDataset对象
		JDBCPieDataset data = null;
		String url = "jdbc:mysql://127.0.0.1:3306/jfreechartdb";
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
		}
		try {
			con = DriverManager.getConnection(url, "root", "root");
			//把JDBCPieDataset对象和Connection关联
			data = new JDBCPieDataset(con);
			String sql = "select * from piedata;";
			//获得数据
			data.executeQuery(sql);
			con.close();
		} catch (SQLException e) {
			System.err.print("SQLException: ");
		} catch (Exception e) {
			System.err.print("Exception: ");
		}
		return data;
	}
}


同时还有其它对象JDBCCategoryDataset,JDBCXYDataset,对应的是条状和,坐标,用于封装相应的数据

你可能感兴趣的:(java,sql,mysql,servlet,jfreechart)