首先,到jfreechart官方網站下載所需的壓縮包文件,雖然jfreechart是開源的,但是技術文檔是收費的,可以到網上搜一搜大神的學習文檔。
解壓文件後,把lib文件夾下的所有文件webcontent/web-inf/lib文件夾下,然後右鍵單擊項目,選擇build path,選擇Libraries,選擇add external jars,把jcommon-版本.jar和
jfreechart-版本.jar這兩個文件添加到Libraries,refresh工程即可。
jfreechart生成的圖片默認是存放在服務器的temp文件夾下,如果想自己指定路徑,可以重寫ServletUtilities類下的saveChartAsPNG方法和saveChartAsJPG(JPEG?)方法:
public class test extends ServletUtilities{
//爲生成的圖片創建文件夾
protected static void createTempDir()
{
//圖片保存路徑
String tempDirName = "c:\\graph\\";
//若不存在則創建
File tempDir = new File(tempDirName);
if (!tempDir.exists())
{
tempDir.mkdirs();
}
}
//重寫ServletUtilities的saveChartAsPNG方法
public static String saveChartAsPNG(JFreeChart chart, int width,
int height, ChartRenderingInfo info, HttpSession session) throws IOException {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
createTempDir();
String prefix = ServletUtilities.getTempFilePrefix();
if (session == null) {
prefix = ServletUtilities.getTempOneTimeFilePrefix();
}
File tempFile = File.createTempFile(prefix, ".png", new File("c:\\graph\\"));
ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
if (session != null) {
ServletUtilities.registerChartForDeletion(tempFile, session);
}
return tempFile.getName();
}
}
完成以上這些,就可以在指定的文件夾下看到生成的圖片,我的是c:\graph\。
雖然文件夾下有圖片了,在Eclipse裏也可以運行出來,但是放到IE裏運行時什麼都看不見,這是因爲頁面只能讀取在項目文件夾下的圖片,項目目錄外的圖片是不能讀取的,
所以想要讀取指定文件夾下的圖片就需要對工程上的Servers/Tomcat v.........../server.xml文件進行配置,在<host>和</host>之間加入如下代碼:
<Context crossContext="true" docBase="c:/graph" path="/graph" reloadable="true"></Context>
其中,docBase是指定文件夾路徑,path是存放圖片的文件夾名(不用全路徑),這樣就使tomcat的存放圖片的文件夾和你存放圖片的文件夾產生映射關係,就可以讀取指定硬盤圖片了。
String filename = saveChartAsPNG(chart, 2000, 400, null, null);
graphURL = "/graph/" + filename;
在jsp頁面訪問的方法<img src="<%=graphURL %>" width="<%=width %>" height="<%=height %>" border=0">