highcharts加载数据库数据(java版)

前段时间因为项目需要使用了highcharts报表,新手可以参考http://www.hcharts.cn/,教程中有比较详细的介绍和demo。但是demo中的例子的数据都是静态数据,而在实际项目中一般数据都是从数据库加载的。
下面是我做的一个简单例子,从数据库中加载数据然后在前端使用highcharts渲染。

读取数据库数据使用的servlet,可以根据需要改成其他(如spring等)。servlet主要代码如下:

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Connection conn = null;
        String sql;
        String url = "jdbc:mysql://192.168.1.203:3306/test?user=opuser&password=opuser1111&useUnicode=true&characterEncoding=UTF8";

        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            sql = "select * from test";
            ResultSet rs = stmt.executeQuery(sql);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (rs.next()) {
                System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datetime", rs.getString(2));
                map.put("data", Double.parseDouble(rs.getString(3)));
                list.add(map);
            }

            Gson gson = new Gson();
            String g = gson.toJson(list);

            PrintWriter out = response.getWriter();  
            out.println(g);
            out.flush();
            out.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

本例中返回的数据格式是json。
程序中使用了mysql和gson的jar包,请自行下载。因为都是比较常用的jar包,在此就不提供下载地址了。

然后是jsp代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>HighChartsTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="js/highcharts.js"></script> --> 
    <script type="text/javascript" src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>
    <script> //图表属性,不包含数据 var options = { chart: { renderTo:'container', type:'spline', }, title: { text: '实时温度曲线', x: -20 //center }, xAxis:{ }, yAxis: { title: { text: 'Temperature (°C)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, series: [{ name:'温度', }], tooltip: { valueSuffix: '°C' }, plotOptions: { spline:{ dataLabels: { enabled: true }, animation:false, }, }, }; //初始函数,设置定时器,定时取数据 $(function () { queryData(0); var i=0; var timer = setInterval(function(){ i++; if(i>=3) {i=0;} queryData(i); },3000); //停止刷新 $("button").click(function(){ clearInterval(timer); }); }); var categories = []; var datas = []; //Ajax 获取数据并解析创建Highcharts图表 function queryData(index) { $.ajax({ url:'servlet/HighCharts', type:'get', dataType:"json", success:function(data) { $.each(data,function(i,n){ categories[i] = n["datetime"]; datas[i] = n["data"]; }); options.xAxis.categories = categories; options.series[0].data = datas; chart = new Highcharts.Chart(options); } }); } </script>
</head>

<body>
    <div id="container" style="min-width:800px;height:400px;"></div>
    <p align=center><button>停止刷新</button></p>

</body>

</html>

代码下载:http://pan.baidu.com/s/1slvI6UL

你可能感兴趣的:(highcharts加载数据库数据(java版))