/**
**QQ:252574345
**MSN:lele_love_lomboz@hotmail.com
*/
跟蹤發(fā)現(xiàn),JFreeChart會把生成的圖片,默認放在應用服務器的temp目錄下,有的時候我們是不能放在該目錄下的,需要改變這個存放路徑
發(fā)現(xiàn)jfreechart的ServletUtilities類里有
protected static void createTempDir() {
String tempDirName = System.getProperty("java.io.tmpdir");
if (tempDirName == null) {
throw new RuntimeException("應用服務器目錄下不存在temp目錄或該目錄無法創(chuàng)建");
}
// create the temporary directory if it doesn't exist
File tempDir = new File(tempDirName);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
}
該方法創(chuàng)建了默認的圖片存放路徑
在該類的saveChartAsPNG() 和saveChartAsJPEG () 里被調用,產生圖形,因此我們的思路就是將ServletUtilities的saveChartAsPNG() 和saveChartAsJPEG () 這2個方法改造成自己定義的方法
修改前源文件如下:
public static String saveChartAsJPEG(JFreeChart chart, int width,
int height, ChartRenderingInfo info, HttpSession session)
throws IOException {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
//注意,源文件使用了默認路徑
ServletUtilities.createTempDir();
String prefix = ServletUtilities.tempFilePrefix;
if (session == null) {
prefix = ServletUtilities.tempOneTimeFilePrefix;
}
File tempFile = File.createTempFile(prefix, ".jpeg",
new File(System.getProperty("java.io.tmpdir")));
ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
if (session != null) {
ServletUtilities.registerChartForDeletion(tempFile, session);
}
return tempFile.getName();
}
修改后如下:
public static String saveChartAsJPEG(JFreeChart chart, int width,
int height, ChartRenderingInfo info, HttpSession session)
throws IOException {
//從application中讀取出臨時文件目錄,我事先已經(jīng)在系統(tǒng)啟動時,創(chuàng)建了目錄
File tempDr=(File)session.getServletContext().getAttribute("tempDirectory");
if (chart == null) {
throw new IllegalArgumentException("chart 對象為空");
}
UIServletUtilities.createTempDir();
String prefix = UIServletUtilities.tempFilePrefix;
if (session == null) {
prefix = UIServletUtilities.tempOneTimeFilePrefix;
}
File tempFile = File.createTempFile(prefix, ".jpeg", tempDr);
ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
if (session != null) {
UIServletUtilities.registerChartForDeletion(tempFile, session);
}
return tempFile.getName();
}
接下來就可以使用
String filename = ServletUtilities.saveChartAsJPEG(chart, 800, 600, info, session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
來生成圖形了