很多情况下jfreechart 在HttpSession失效时不能按预期的自动删除所生成的图片。
通过分析ChartDeleter的原码
public void valueUnbound(HttpSessionBindingEvent event) {
Iterator iter = this.chartNames.listIterator();
while (iter.hasNext()) {
String filename = (String) iter.next();
File file = new File(System.getProperty("java.io.tmpdir"), filename);
if (file.exists()) {
file.delete();
}
}
return;
}
可知,原因在于通常生成的图片的路径并不总是System.getProperty("java.io.tmpdir")。
解决办法:
修改ChartDeleter.java原文件如下
...
public ChartDeleter(HttpSession httpSession) {
super();
this.httpSession = httpSession;
}
public void valueUnbound(HttpSessionBindingEvent event) {
Iterator iter = this.chartNames.listIterator();
while (iter.hasNext()) {
String filename = (String) iter.next();
File file = new File(this.httpSession.getServletContext().getRealPath("/"), filename);
if (file.exists()) {
file.delete();
}
}
return;
}
...
修改ServletUtilities.java如下:
。。。
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.");
}
ServletUtilities.createTempDir();
String prefix = ServletUtilities.getTempFilePrefix();
if (session == null) {
prefix = ServletUtilities.getTempOneTimeFilePrefix();
}
File tempFile = File.createTempFile(prefix, ".png",
new File(session.getServletContext().getRealPath("/")));
ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
if (session != null) {
ServletUtilities.registerChartForDeletion(tempFile, session);
}
return tempFile.getName();
}
。。。
就是把图片存在项目根目录下。
其实更合适的方式是不修改源文件,通过继承、重写方法的途径是更好的选择。