在
Servlet中的代码:
package com.lyb.pic;
import java.awt.BasicStroke;
import java.awt.Font;
import java.io.IOException;
importjavax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
public
class Time extends HttpServlet{
public voiddoGet(HttpServletRequest request,HttpServletResponse response)throws IOException {
doPost(request,response);
}
public void doPost(HttpServletRequestrequest,HttpServletResponse response) throws IOException {
//设置返回类型
response.setContentType("image/png");
//设置返回字体
response.setCharacterEncoding("utf-8");
//获取数据集对象
XYDataset xyd =getData();
// 创建图形对象
JFreeChart jfc =ChartFactory.createTimeSeriesChart("时序图","POLO历史价格", "价格", xyd,true, true, false);
//设置标题字体,防止中
文乱码
jfc.getTitle().setFont(newFont("黑体", 0, 15));
//设置图例的字体,防止中文乱码
jfc.getLegend().setItemFont(newFont("黑体", 0, 15));
//获取图表区域对象
XYPlot xyplot = (XYPlot)jfc.getPlot();
//设置横轴标签的字体,防止中文乱码
xyplot.getDomainAxis().setLabelFont(newFont("黑体", 0, 15));
//设置竖轴标签的字体,防止中文乱码
xyplot.getRangeAxis().setLabelFont(newFont("黑体", 0, 15));
//获得折线显示对象
XYLineAndShapeRendererxylineand
shaperenderer = new XYLineAndShapeRenderer();
//设置不显示折线
xylineandshaperenderer.setBaseShapesVisible(false);
//设置折线的粗细
xylineandshaperenderer.setSeriesStroke(0,new BasicStroke(0.5F, 1, 1, 5F, new float[] { 5F, 10F },0.0F));
xyplot.setRenderer(xylineandshaperenderer);
// 将图表已数据流的方式返回给客户端
ChartUtilities.writeChartAs
PNG(response.getOutputStream(),jfc,500, 270);
}
private static XYDataset getData() {
//创建时序对象
TimeSeries timeseries = newTimeSeries("动画");
//初始化日期为1990年1月1日
Day day = new Day(1, 1,1990);
double d = 100D;
//添加数据,用于标识横轴的显示数字
for (int i = 0; i< 4000; i++)
try {
//随机取出100附近数
d= (d + Math.random()) - 0.5D;
//添加到时序对象
timeseries.add(day,new Double(d));
//之后的一天
day= (Day) day.next();
} catch(SeriesException seriesexception) {
}
//返回XYDataset数据集
return newTimeSeriesCollection(timeseries);
}
}
产生的假数据:
package com.lovo.pic;
import java.util.Random;
public class DataUtils {
private static Random random = newRandom();
private static final int NUMBER = 100;
public static int getNumber() {
returnrandom.nextInt(NUMBER);
}
}
在xml中的代码:
<servlet>
<servlet-name>time</servlet-name>
<servlet-class>com.lovo.pic.Time</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>time</servlet-name>
<url-pattern>/time</url-pattern>
</servlet-mapping>