【问题标题】:Integrating JFreeChart with SpringMVC throws exception: getOutputStream() has already been called for this response将 JFreeChart 与 SpringMVC 集成会引发异常:已为此响应调用 getOutputStream()
【发布时间】:2012-09-22 00:00:45
【问题描述】:

我想在我的 web 应用程序中显示一个简单的图表,所以我决定将 JFreeChart 集成到 Spring MVC 中。 我找到了以下解决方案:

@RequestMapping("/seeGraph")
    public String drawChart(HttpServletResponse response) {

        response.setContentType("image/png");
        XYDataset pds = createDataset();
        JFreeChart chart = createChart(pds);
        try {
            ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 600, 400);            
            response.getOutputStream().close();

        } catch (Exception e) {

        }
        return "graph";
    }

我想这不好。虽然它确实显示了图表,但它也会引发异常:

getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response.

我做了一些研究,发现应用程序可以在任何给定的响应上调用 getOutputStream 或 getWriter,这是不允许的。

但是由于 ChartUtilities.writeChartAsPNG() 我必须调用 getOutputstream,而 Spring 将调用 getWriter()。

有什么聪明的办法可以避免这个异常吗?

【问题讨论】:

    标签: spring-mvc jfreechart


    【解决方案1】:

    目前,您要求 Spring 在执行控制器方法后渲染一个名为 graph 的视图(通过从方法返回视图名称)。但是,如果您将数据写入控制器内的输出,则不应继续查看渲染阶段。

    因此,您需要改用void 方法:

    @RequestMapping("/seeGraph")
    public void drawChart(HttpServletResponse response) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多