highcharts加載數據庫數據(java版)

前段時間由於項目須要使用了highcharts報表,新手能夠參考http://www.hcharts.cn/,教程中有比較詳細的介紹和demo。可是demo中的例子的數據都是靜態數據,而在實際項目中通常數據都是從數據庫加載的。
下面是我作的一個簡單例子,從數據庫中加載數據而後在前端使用highcharts渲染。javascript

讀取數據庫數據使用的servlet,能夠根據須要改爲其餘(如spring等)。servlet主要代碼以下:html

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代碼以下:java

<%@ 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/1slvI6ULmysql

相關文章
相關標籤/搜索