写一个工具类,集成ServletUtilities,重写其生成图片方法,如下:
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
public class JFChartUtils extends ServletUtilities {
private static String tempFilePrefix = "jfreechart-";
private static String tempOneTimeFilePrefix = "jfreechart-onetime-";
public static String saveChartAsPNG(String path,JFreeChart chart, int width,
int height, ChartRenderingInfo info, HttpSession session)
throws java.io.IOException {
try{
if (chart == null)
throw new IllegalArgumentException("Null 'chart' argument.");
createTempDir(path);
String prefix = tempFilePrefix;
if (session == null)
prefix = tempOneTimeFilePrefix;
File tempFile = File.createTempFile(prefix, ".png", new File(path));
ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
if (session != null)
registerChartForDeletion(tempFile, session);
return tempFile.getName();
}catch(Exception ex){
ex.printStackTrace();
System.out.println("null!");
return "";
}
}
protected static void createTempDir(String path) {
request.getContextPath()+"/jfchart";
if (path == null)
throw new RuntimeException(
"Temporary directory system property (java.io.tmpdir) is null.");
File tempDir = new File(path);
if (!tempDir.exists())
tempDir.mkdirs();
}
}
由上可以看出,在进行图片生成时在方法中增加了图片生成目录String path,在控制层,获取项目路径,然后传输给业务处理层,在业务处理层通过JFreeChartUtils. saveChartAsPNG 方法生成图片。