jfreechart不能自动删除生成的图片

本文介绍了解决JFreeChart在HttpSession失效时未能自动删除生成图片的问题。通过修改ChartDeleter与ServletUtilities类,确保图片正确保存并可在会话结束时被删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多情况下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();
  
 }

。。。

就是把图片存在项目根目录下。

其实更合适的方式是不修改源文件,通过继承、重写方法的途径是更好的选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值