在web页面中想调用数据库数据,然后用jfreechart进行画图,发现一般例子提供的都是jfreechart默认保存于tomcat的temp文件下(例子自),而想要保存到工程文件夹下(例子二),并在jsp页面进行显示。
功能:完成对湿度信息随时间的画图,并在页面上显示曲线图
公共代码:
String [] str = new String[list_photo.size()];//湿度和对应的时间信息存放在list_photo中
double avgdouble =0;
String shidu;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
//sdf.applyPattern("yyyy-MM-dd hh:mm:ss");
for(int j=0;j<list_photo.size();j++){
shidu=list_photo.get(j).getShidu();
str[j]=shidu;
avgdouble += Double.parseDouble(str[j]);
String date =sdf.format(list_photo.get(j).getTime());
dataset.addValue(Double.parseDouble(str[j]), "湿度",date );
}
avgdouble = avgdouble/list_photo.size();
String avg=String.format("%5.2f",avgdouble);
dataset.addValue(Double.parseDouble(avg), "湿度", "avg");
JFreeChart chart = ChartFactory.createLineChart("湿度变化 ", "时间", "湿度", dataset, PlotOrientation.VERTICAL, true, true, true);
//设置子标题
CategoryPlot plot = chart.getCategoryPlot();
//设置字体,不然会中文乱码的
Font font = new Font("宋体", Font.BOLD, 16);
TextTitle title = new TextTitle("实时湿度", font);
//副标题
// TextTitle subtitle = new TextTitle("5组数据及平均值", new Font("黑体", Font.BOLD, 12));
// chart.addSubtitle(subtitle);
chart.setTitle(title); //标题
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
CategoryAxis domainAxis = plot.getDomainAxis();
/*------设置X轴坐标上的文字-----------*/
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // X轴上的Lable让其45度倾斜
domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
/*------设置X轴的标题文字------------*/
domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
/*------设置Y轴坐标上的文字-----------*/
numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
/*------设置Y轴的标题文字------------*/
numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));
/*------这句代码解决了底部汉字乱码的问题-----------*/
chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
//设置网格背景颜色
plot.setBackgroundPaint(Color.yellow);
//设置网格竖线颜色
plot.setDomainGridlinePaint(Color.black);
//设置网格横线颜色
plot.setRangeGridlinePaint(Color.black);
例子1一保存在tomcat的temp文件下
在上面代码下添加如下代码:
String fileName = ServletUtilities.saveChartAsJPEG(
chart, 500, 300, request.getSession());
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + fileName;
// 将路径放到request对象中
request.getSession().setAttribute("graphURL", graphURL);
// 页面转发到result.jsp
request.getRequestDispatcher("shidu_photo.html").forward(request, response);
进行web.xml设置
<servlet>
<description>JFreeChart</description>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/DisplayChart</url-pattern>
</servlet-mapping>
jsp页面显示
在页面上方添加 导入语句 <%@page import="org.jfree.chart.servlet.ServletUtilities,com.jwy.servlet.ChartUtil" %>
显示:
<div class="leftContext">
<img src="${graphURL}" border="1">
<br><br>
<a href="index.jsp">返回</a>
</div>
例子2一保存到工程文件下
在公共代码下添加如下代码
String filename = saveChartAsPNG(chart, 700, 300, null,request.getSession());
request.getSession().setAttribute("filename",filename);
request.getRequestDispatcher("shidu_photo.html").forward(request, response);
另外添加函数:
protected void createTempDir()
{
String tempDirName = getServletContext().getRealPath("/graph");
if (tempDirName == null)
{
throw new RuntimeException("Temporary directory system property " + "(java.io.tmpdir) is null.");
}
// create the temporary directory if it doesn't exist
File tempDir = new File(tempDirName);
if (!tempDir.exists()){
tempDir.mkdirs();
}
}
//覆盖父类的方法
public String saveChartAsPNG(JFreeChart chart, int width, int height,
ChartRenderingInfo info, HttpSession session1) throws IOException
{
if (chart == null)
{
throw new IllegalArgumentException("Null 'chart' argument.");
}
createTempDir();
String prefix = ServletUtilities.getTempFilePrefix();
File tempFile = File.createTempFile(prefix, ".png", new File(getServletContext().getRealPath("/graph") ));
ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
return tempFile.getName();
}
不需要对web.xml文件进行设置
页面显示:
<% String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// System.out.println(basePath);%>
<div class="leftContext"><img src ="<%=basePath%>graph/${filename}" class="im">
</div>