带有servlet的JFREECHART

时间:2015-05-26 06:58:03

标签: java jsp servlets

我试图让JFREECHART为图表中的某些硬编码数据创建一个png。 我完全没有错误,我通过创建部分运行的程序,但我没有得到一个png。

任何人都可以看到问题所在?

我的servlet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = request.getParameter("Action");
    if(action.equals("Home"))
        getServletContext().getRequestDispatcher(home).forward(request, response);

    else{
        session = request.getSession(true);
        user = (User) session.getAttribute("User");
        eventList = rh.getEventList(user);
        request.setAttribute("EventList", eventList);
        getServletContext().getRequestDispatcher(result).forward(request, response);

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.setValue(30, "Girls","SCIENCE CLASS");
        dataset.setValue(30,  "Boys","SCIENCE CLASS");
        dataset.setValue(10,  "Girls","ECONOMICS CLASS");
        dataset.setValue(50, "Boys","ECONOMICS CLASS");
        dataset.setValue(5, "Girls","LANGUAGE CLASS");
        dataset.setValue(55, "Boys","LANGUAGE CLASS");

        JFreeChart chart = ChartFactory.createLineChart(
                "Comparison between Girls and Boys in Science," + "Economics and Language classes",
                "Students Comparisons", "No of Students",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);


            try {

                final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                final File file1 = new File(getServletContext().getRealPath(".") + "/images/lineChart.png");

                ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
            } catch (Exception e) {
                System.out.println(e);

            }
    }
}

和我的jsp

                <div>
                <img src="path/images/lineChart.png"
                     width="600" height="400" border="0" usemap="#chart" />
            </div>

1 个答案:

答案 0 :(得分:0)

为了实现这一点,必须在呈现JSP之前调用Servlet。然而,你采取的方法存在各种其他缺陷。

我建议不要将生成的图表写入文件,而是直接将其流式传输到Servlet的响应流:

http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/ChartUtilities.html#writeChartAsPNG-java.io.OutputStream-org.jfree.chart.JFreeChart-int-int-

 try {
    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    ChartUtilities.writeChartAsPNG(response, chart, 600, 400, info);
} catch (Exception e) {
    System.out.println(e);
}

然后,您只需将<img/>标记指向您的Servlet:

<div>
    <img src="pathToMyServlet" width="600" height="400" border="0" usemap="#chart" />
 </div>