首先,到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">