JFreeChart ChartUtilities.saveChartAsPNG在Servlet中不起作用

时间:2016-02-11 03:32:30

标签: java servlets jfreechart

ChartUtilities.saveChartAsPNG在类文件中运行良好,但在运行servlet文件后无法获取png文件。我在lib中获得了jcommon jfreechart mysql-connector-java servlet四个jar文件。并在web.xml中配置了servlet。那我该怎么做才能解决这个问题呢?感谢

    response.setContentType("image/png");
    ServletOutputStream os = response.getOutputStream();

    Connection connect = null;
    Statement statement = null;
    ResultSet resultSet = null;

    connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/XXX","root","123");
    statement = connect.createStatement( );
    resultSet = statement.executeQuery("select acres, tax from XXXX" );

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    while( resultSet.next( ) ) 
      {
          dataset.addValue(
                resultSet.getInt("tax"), 
                "Tax", 
                String.valueOf(resultSet.getInt("acres"))
            );
      }

    JFreeChart chart = ChartFactory.createLineChart(
               "Tax Revenue",
               "",
               "Dollars",
               dataset, 
               PlotOrientation.VERTICAL,
              true, true, false);

    RenderedImage chartImage = chart.createBufferedImage(700, 500);
    ImageIO.write(chartImage, "png", os);

    int width = 1500; /* Width of the image */
    int height = 500; /* Height of the image */ 

    ChartUtilities.saveChartAsPNG(new File("chart.png"), chart, width, height);
            try{
        if(statement!=null)
            statement.close();
    }catch(SQLException se2){}
        try{
            if(connect!=null)
                connect.close();
        }catch(SQLException se){
        se.printStackTrace();
    }
    os.flush();
    os.close();

0 个答案:

没有答案