2012-10-26 48 views
0

我已經在struts2.in中創建了web項目,我使用jfreechart繪製了一個圖表,這是我在Action類中實現的。將圖表添加到緩衝區中

http://www.java2s.com/Code/Java/Chart/JFreeChartTimeSeriesDemo10withperminutedata.htm

它顯示在單獨的小程序窗口實物我用Google搜索的圖形,並找到一個辦法救這個圖表作爲圖像,這樣在我的JSP文件,我可以包括這一形象。 但最後當我部署我不得不將我的項目轉換成WAR文件,但如果我將項目轉換爲WAR我不能訪問圖像(圖),根據用戶請求更改。所以我想保存圖表/圖像在緩衝區或某件事物中,以便稍後在請求新圖形或用戶註銷時刪除它們。

所以,你可以給一些關於如何做到這一點的想法。 在此先感謝

回答

2

我寫了類似於您正在嘗試做的事情。我完成這個任務的方式是擁有第二個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."); 
    } 
} 
+0

trashgod我認爲烏爾幫助第2或第3次感謝的人,我會嘗試this.though我沒有對servlet的聲音knowldege,JSP,J2EE讓希望我這樣做正確和它的作品 – HkFreaKuser1673718

+0

只是一個側面說明,trashgod編輯帖子,我發佈了內容。無論哪種方式,很高興它有幫助。 – Lipongo

+0

Lipongo sry沒有注意到你的傢伙謝謝你,但我想我不能這樣做因爲我使用的是struts 2,如果把 ......等放在我的web.xml中,我的web項目不起作用如果我刪除這個servlet映射項目works.so我不得不放棄此功能。謝謝 – HkFreaKuser1673718

相關問題