Dynamically generate JFreeChart in servlet

筅森魡賤 提交于 2019-11-29 10:51:05

Have your JSP file include an tag where the src attribute is the name of your servlet. Then, you simply have the servlet return the PNG chart:

    OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    ChartUtilities.writeChartAsPNG(out, chart, width, height);

JSP pages are really only intended to output HTML or other text data. Although you could force the JSP to output the PNG, there is no benefit to doing it that way.

It sounds like you want to create a dynamic page that updates based on a drop-down menu state change. For this, you need to use Javascript that triggers when the menu changes, and updates the value of the img tag's src attribute. Then the browser will reload the image from your servlet with a new chart.

I would suggest that you use the ServletUtilities class. It saves in the java tempdir AND cleans up when the session is invalidated. :) Another hint for then displaying the file is to use the DisplayChart servlet to get your images. This goes in web.xml

      <servlet>
    <servlet-name>DisplayChart</servlet-name>
    <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
  </servlet>
   <servlet-mapping>
        <servlet-name>DisplayChart</servlet-name>
        <url-pattern>/servlet/DisplayChart</url-pattern>
    </servlet-mapping>

This is then how you display the image using jstl:

<img src="<c:url value='/servlet/DisplayChart?'><c:param name='filename' value='${yourFileNameHERE}' /></c:url>" alt=""/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!