adding graph chart to a buffer

随声附和 提交于 2019-11-29 18:08:33
Lipongo

I have written something similar to what you are trying to do. The way I accomplished this was to have a second servlet (very simple) that takes in parameters based on the requested chart and generates the chart as a PNG. Basically, you call the servlet with the required parameters. You take those parameters and build your chart. The important part of returning the chart is happening in ChartUtilities.writeChartAsPNG(out, chart, 640, 480) where the first parameter is the output stream for the response to the calling page. The second parameter is the chart you have built. The last two parameters are used for the size of the image. When you call this servlet it would be inside of

<img src="URL_to_Servlet" />

with the URL containing the needed parameters to build the chart.

Below is the code you will need, focusing solely on returning the chart as a dynamically built image from a Servlet.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

public class ChartServlet extends HttpServlet {

    /*
     * (non-Javadoc) @see
     * javax.servlet.http.HttpServlet#doGet(
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        JFreeChart chart = this.generateLineChart();
        ServletOutputStream out = resp.getOutputStream();
        resp.setContentType("image/png");
        ChartUtilities.writeChartAsPNG(out, chart, 640, 480);
        out.close();
    }

    /**
     * Generate chart.
     *
     * @return the j free chart
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private JFreeChart generateLineChart() throws IOException {

        return chart;
    }

    /*
     * (non-Javadoc) @see javax.servlet.GenericServlet#init()
     */
    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("Starting up charts servlet.");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!