1. 程式人生 > >動態從資料庫獲取資料實時插入圖表

動態從資料庫獲取資料實時插入圖表

1.實現效果圖


2.jsp檔案

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../../bootstrap/js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="https://img.hcharts.cn/highcharts/highcharts.js"></script>
<script type="text/javascript" src="https://img.hcharts.cn/highcharts/modules/exporting.js"></script>
</head>
<body>
	資料庫獲取的時間:<span id="getTime"></span>

	<button id="stopit">停止定時器</button> 
	<button id="startit">開啟定時器</button>
	
	
	<div id="container" style="min-width:400px; height: 400px;"></div>
	<script>        
		Highcharts.setOptions({
				    global: {
				        useUTC: false
				    }
				});
				function activeLastPointToolip(chart) {
				    var points = chart.series[0].points;
				    chart.tooltip.refresh(points[points.length -1]);
				}
				
				$('#container').highcharts({
				    chart: {
				        type: 'spline',
				        animation: Highcharts.svg,
				        marginRight: 10,
				        events: {
				            load: function () {
				                //每秒從資料庫獲取一個數
				                var series = this.series[0],
				                    chart = this;
				                //定時器
				                var iCount = setInterval(function(){
								    var url = "${pageContext.request.contextPath}/AjaxTimeServlet";
								    $("#getTime").load(url,function(backData,textStatus,xmlHttpRequest){
										var $temperature = parseFloat(backData.substr(0,4));//對傳過來的資料進行型別轉換
										var $time = (new Date(Date.parse((backData.substr(5,21)).replace(/-/g,"/")))).getTime();
										//每隔一秒新增進去的數
									    var x = $time;
									    	y = $temperature;
									    series.addPoint([x, y], true, true);
								        activeLastPointToolip(chart)
									});
								}, 1000);
				                //關閉定時器
						        $("#stopit").click(function(){
						        	 clearInterval(iCount);
						        });
								
				            }
				        }
				    },
				    title: {
				        text: '動態模擬實時資料'
				    },
				    xAxis: {
				        type: 'datetime',
				        tickPixelInterval: 150
				    },
				    yAxis: {
				        title: {
				            text: '值'
				        },
				        plotLines: [{
				            value: 0,
				            width: 1,
				            color: '#808080'
				        }]
				    },
				    tooltip: {
				        formatter: function () {
				            return '<b>' + this.series.name + '</b><br/>' +
				                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
				                Highcharts.numberFormat(this.y, 1);
				        }
				    },
				    legend: {
				        enabled: false
				    },
				    exporting: {
				        enabled: false
				    },
				    series: [{
				        name: '資料',
				        data: (function () {
				            var data = [],
				                time = (new Date()).getTime(),
				                i;
				            for (i = -19; i <= 0; i += 1) {
				                data.push({
				                    x: time + i * 1000,
				                    y: Math.random()+19
				                });
				            }
				            return data;
				        }())
				    }]
				}, function(c) {
				    activeLastPointToolip(c)
				});
	</script>
</body>
</html>

3.功能實現

package com.chinasoft.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chinasoft.dao.impl.ImplTemperatureDao;
import com.chinasoft.entity.Temperature;

@WebServlet("/AjaxTimeServlet")
public class AjaxTimeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public AjaxTimeServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Temperature temperature = new Temperature();
//		生成隨機溫度
		Random random = new Random();
		float a = random.nextFloat()/2+19;
		BigDecimal b =new BigDecimal(a).setScale(1,BigDecimal.ROUND_HALF_UP);
		temperature.setTemperature(b+"℃");
		ImplTemperatureDao implTemperatureDao = new ImplTemperatureDao();
		try {
				//插入資料庫
				implTemperatureDao.addTemperature(temperature);
				//讀取資料
				temperature =implTemperatureDao.findTemperatureById();
				//轉換時間格式
				SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time = myFmt.format(temperature.getTime());
				//傳送
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().write(temperature.getTemperature());
				response.getWriter().write(time);
				/*//儲存到json中
				Map<String,String> map = new HashMap<>();
				map.put("temperature", temperature.getTemperature());
				map.put("time", time);
				String result = JSONObject.fromObject(map).toString();
				//傳送到客戶端
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().write(result);*/
				
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

相關推薦

動態資料庫獲取資料實時插入圖表

1.實現效果圖 2.jsp檔案 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="f

ajax寫級聯效果,動態資料庫獲取資料

要實現的級聯資料的效果是,諮詢方式有多種,有的有子諮詢方式,有的沒有,直接上圖圖一中選擇自選方式,例如:選擇面詢,效果如圖二,後面對應的有面詢的子諮詢方式,有的沒有子諮詢方式,如圖三,沒有子諮詢方式,後面不顯示

Echarts 動態後臺獲取資料進行圖表的展示

前端部分: <!DOCTYPE html>   <head> <meta charset="utf-8"> <title>ECharts</title> </head>   <body>     <!-- 為EChart

Echart實現資料庫獲取資料展示圖表(結合Servlet和SSM實現的兩種例項)

        2018年5月30日(UPDATE): Google郵箱不怎麼上,建議Email [email protected]------------------------------

c# 本地資料庫獲取資料並以圖表顯示

一. 本地mysql資料庫我的本地資料庫設計是這樣的資料庫伺服器名稱: restful_api使用表: locationusername: rootpassword: root後面資料庫連線部分請自行根據自己資料更改二. 實現過程資料模板基類:這個類就是用於get和set操作

資料庫獲取資料插入頁面

控制器中程式碼 記得在路由表中新增路由: public function postCategoryList() { $result = DB::connection('news')->table('categories')->select('id','pi

省級聯動資料庫獲取資料

主要就是前臺js程式碼,後臺就是根據id直接查詢的 html程式碼 <select style="width:130px" name="provinceCode" id="province"> <option value="0">--請選擇--<

PullToRefersh、網路獲取資料新增到adapter和資料庫 然後顯示、無網路時資料庫獲取資料新增到另一個adapter 然後顯示

package liyuanqi.bwie.com.pulltorrfresh; import android.content.Context; import android.net.ConnectivityManager; import android.net

python專案篇-資料庫獲取資料以Json格式返回前端資料視覺化方式顯示

views.py: def adminEchartIncome(request): ret = models.incomeAccount.objects.all().order_by("dayIncome","id") # ret = serialize("json

easyui combobox下拉框省市縣三級聯動(資料庫獲取資料)

//combobox的onLoadSuccess,onChange,onSelect事件    省:<input id="province" style="width: 110px;" /> 市:<input id="city" style="width

symfony2實現資料庫獲取資料的方法

假設有一張表:test,欄位:name,color 有兩條記錄:Tom blue                          Lily red 1        $conn=$this->getDoctrine()->getConnection();  

javascript資料庫獲取資料後,生成EasyUI樹

不用管是什麼資料庫,php還是java語言只要資料庫表字段是有自身指向的結構的都行。廢話少說,直接上程式碼<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <titl

介面測試: 用Jmeter資料庫獲取測試資料, 作為下一個介面引數方法

現在有一個需求,從資料庫tieba_info表查出rank小於某個值的username和count(*),然後把所有查出來的username和count(*)作為引數值,用於下一個介面。 (資料庫連線配置,請參考我的另外一篇博文jmeter測試mysql資料庫之JDBC請求https://blo

陌陌迴應資料洩露:誰都無法直接資料庫獲取明文密碼

   12月3日訊息。有微博網友曝出陌陌2015年的賬戶密碼資訊在暗網上公開售賣,資料量達到3000萬條,而要價只有區區50美元,摺合人民幣還不到350元。 不過賣家表示,這批資料是2015年7月17日寫入的,也就是已經三年多,因此不保證現時有效性,只適合撞庫使用,且一經售出

資料庫獲取到json資料,前端用vue.js資料繫結

function userinfor() { $.get("http://127.0.0.1:8082/lzghcg/user/userShows", function(result, state) { //這裡顯示從伺服器返回的資料 new Vue

資料庫讀取資料動態生成樹形選單示例

用C#從資料庫讀取資料,動態生成樹形選單例子 資料庫表 前臺程式碼 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="demo.aspx.cs" Inherits="demo" %> <!DO

第一次使用echart後臺獲取資料動態顯示到頁面

第一次使用Echart繪製圖表,看了兩天,終於結合後臺給整出來了。走過之後再看看,其實很簡單的。不多說了,直接上圖: 第一步:去echarts官方下載最新的js; 官方地址 : echarts.baidu.com             我下的是3.4.0版的:echar

JS後臺獲取資料,前臺動態新增tr標籤中的td標籤

功能描述: 要求從後臺查詢該省份的所有城市,然後動態的再前臺固定的tr標籤中新增相應的td標籤來展示城市基本資訊; 一、前臺jsp及js原始碼 jsp:在固定的tr標籤中新增一個

C# Oracle資料庫獲取資料並在combobox進行顯示

折騰了半天,其實比較簡單,程式碼如下,其中需要先新增引用 using System.Data.OracleClient; private void select() { string con

使用echart後臺獲取資料動態顯示到頁面

第一次使用Echart繪製圖表,看了兩天,終於結合後臺給整出來了。走過之後再看看,其實很簡單的。不多說了,直接上圖: 第一步:去echarts官方下載最新的js; 官方地址 : echarts.baidu.com             我下的是3.4.0