2012-09-21 72 views
1

我想顯示在我的web應用一個簡單的圖形,所以我已經決定的JFreeChart集成到Spring MVC的。 我發現了以下解決方案:用SpringMVC與集成的JFreeChart拋出異常:的getOutputStream()已經被調用,這種響應

@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()。

有什麼巧妙的解決了避免這種例外?

回答

1

目前你問春(由該方法返回一個視圖名稱)來呈現一個名爲您的控制器方法執行後視圖。然而,如果你將數據寫入到控制器裏面的輸出,你不應該繼續查看呈現階段。

所以,你需要使用一個void方法來代替:

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

感謝,這是有道理的 –

相關問題