我写了一些类似于你正在尝试做的事情。我实现这一点的方法是拥有第二个 servlet(非常简单),它根据请求的图表接收参数并将图表生成为PNG
. 基本上,您使用所需的参数调用 servlet。您获取这些参数并构建图表。返回图表的重要部分发生在ChartUtilities.writeChartAsPNG(out, chart, 640, 480)
第一个参数是对调用页面的响应的输出流中。第二个参数是您构建的图表。最后两个参数用于图像的大小。当您调用此 servlet 时,它将位于
<img src="URL_to_Servlet" />
使用包含构建图表所需参数的 URL。
下面是您将需要的代码,仅专注于将图表作为动态构建的图像从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.");
}
}