<1>页面chart.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>highchart折线图</title>
<Meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script src="highcharts.js"></script>
<script type="text/javascript">
var xset = [];//X轴数据集
var yset = [];//Y轴数据集
/*返回数据*/
function getData(){
$.getJSON('com/ChartServlet',function(data){
$.each(data,function(i,item){
$.each(item,function(k,v){
xset.push(k);
yset.push(v);
});
})
console.log(xset);
console.log(yset);
//根据时间序列生成折线图
showChart(xset,yset);
});
}
/*定义图表*/
function showChart(xset,yset){
var chart = new Highcharts.Chart({
chart: {
renderTo: 'linecontainer',type: 'line',marginRight: 130,marginBottom: 25
},xAxis: {
categories: xset
},yAxis: {
title: {
text: '数据'
},plotLines: [{
value: 0,width: 1,color: '#808080'
}]
},tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},legend: {
layout: 'vertical',align: 'right',verticalAlign: 'top',x: -10,y: 100,borderWidth: 0
},series: [{
name: '随机时间序列',data: yset
}]
});
}
//执行
getData();
</script>
</head>
<body>
<!-- 图表显示区 -->
<div id="linecontainer" style="width: 1200px; height: 300px"></div>
</body>
</html>
<2>ChartServlet.java
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ChartServlet extends HttpServlet {
public ChartServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
this.doPost(request,response);
}
public void doPost(HttpServletRequest request,IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//生成一组随机的时间序列
JSONArray jsonArr = new JSONArray();
JSONObject item = null;
for (int i = 0; i < 10; i++) {
item = new JSONObject();
//从今日开始统计
item.put(sdf.format(add(new Date(),i)),Math.round(1000*Math.random()));
jsonArr.add(item);
}
out.println(jsonArr.toString());
out.flush();
out.close();
}
//日期加N天
public Date add(Date day,int dist) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(day);
calendar.add(calendar.DATE,dist);
day = calendar.getTime();
return day;
}
public void init() throws ServletException {
// Put your code here
}
}
原文链接:https://www.f2er.com/ajax/166178.html