Echarts-Struts2+Spring+Mybnatis+Jquery+Json在頁面顯示數據(數據從數據庫讀取)

功能:從數據庫查詢兩個數據(溫度與一氧化碳濃度),顯示到頁面,頁面嵌入echarts的儀表盤

思路:

1、通過mybatis從數據庫獲取數據(封裝爲list)

2、Spring管理mybatis的mapper與struts2的action

3、Struts2的action完成數據的封裝(轉爲Json數組)

4、jsp頁面通過ajax獲取action的數據


關於mybatis到action的查詢數據功能,會在後續的框架搭建中講述,現在直接進入action到頁面的顯示塊


1、action代碼:

package com.bs.view.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.bs.container.ServiceProvider;
import com.bs.po.Data;
import com.bs.service.DataService;
import com.opensymphony.xwork2.ActionSupport;

import net.sf.json.JSONArray;
/*
 *@Author swxctx
 *@time 2017年4月30日
 *@Explain:查詢數據庫數據,轉換爲json數據到前臺頁面顯示
 */
public class DataAction extends ActionSupport{
	
	private static final long serialVersionUID = 1L;
	
	/*加載applicationContext.xml*/
	private DataService dataService = (DataService)ServiceProvider.getService(DataService.SERVICE_NAME);
	
	@SuppressWarnings("unchecked")
	public String getData() throws Exception{
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();

		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*獲取到數據庫返回的data list(調用service層方法)*/
		List<Data> datas = dataService.findLastData();
		
		//獲取temp與co
		@SuppressWarnings("rawtypes")
		List tempList = new ArrayList();//溫度
		@SuppressWarnings("rawtypes")
		List coList = new ArrayList();//二氧化碳
		
		for(Data data:datas){
			//將獲取到的數據分別放到各自的數組中
			tempList.add(data.getTemp());
			coList.add(data.getCo());
		}
		
		//將數據放入到同一個list
		@SuppressWarnings("rawtypes")
		List<List> lists = new ArrayList();
		/*先放入temp*/
		lists.add(tempList);
		/*co*/
		lists.add(coList);
		
		/*轉換爲json數組*/
		JSONArray jsonArray = JSONArray.fromObject(lists);
		
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("aplication/json;charset=UTF-8");
			response.getWriter().print(jsonArray);//發送到頁面
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		return null;
	}
}

2、jsp頁面

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">
 
 <!-- ECharts單文件引入 -->
  <script src="js/dist/echarts.js"></script>
  <!-- jquery引入 -->
  <script src="js/jquery.js"></script>
  
<title>Insert title here</title>
</head>
<body>

	<!-- 爲ECharts準備一個具備大小(寬高)的Dom -->
    <div id="temp" style="height:330px;width:500px"></div>
    <div id="co" style="height:330px;width:500px"></div>
    
</body>

	
<script type="text/javascript">
	var tempArray = new Array();
	var coArray = new Array();
	$.ajax({
		url : 'getData.action',
		type : 'GET',
		dataType : 'json',
		async : false,
		success : function(jsonArray) {
			for (x in jsonArray[0]) {
				tempArray[x] = jsonArray[0][x];//將action發送來的數據放入數組
			}
			for (x in jsonArray[0]) {
				coArray[x] = jsonArray[1][x];
			}
		}
	});
	
	
	// 路徑配置
	require.config({
	    paths: {
	        echarts: 'js/dist'
	    }
	});

     // 使用
     require(
         [
             'echarts',
             'echarts/chart/gauge' // 淺色儀表盤
         ],
         SetEcharts
       );
     
     function SetEcharts(ec){
  	   TempGauge(ec);//調用顯示
  	   CoGauge(ec);
     }
       
    /*溫度值監測圖表*/
   function TempGauge(ec) {
     // 基於準備好的dom,初始化echarts圖表
     var TempChart = ec.init(document.getElementById('temp')); 
       
     var option = {
	    tooltip : {
	        formatter: "{a} <br/>{b} : {c}℃"
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: true},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    series : [
	        {
	            name:'當前溫度值',
	            type:'gauge',
	            splitNumber: 10,       // 分割段數,默認爲5
	            axisLine: {            // 座標軸線
	                lineStyle: {       // 屬性lineStyle控制線條樣式
	                    color: [[0.2, '#228b22'],[0.8, '#48b'],[1, '#ff4500']], 
	                    width: 8
	                }
	            },
	            axisTick: {            // 座標軸小標記
	                splitNumber: 10,   // 每份split細分多少段
	                length :12,        // 屬性length控制線長
	                lineStyle: {       // 屬性lineStyle控制線條樣式
	                    color: 'auto'
	                }
	            },
	            axisLabel: {           // 座標軸文本標籤,詳見axis.axisLabel
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    color: 'auto'
	                }
	            },
	            splitLine: {           // 分隔線
	                show: true,        // 默認顯示,屬性show控制顯示與否
	                length :30,         // 屬性length控制線長
	                lineStyle: {       // 屬性lineStyle(詳見lineStyle)控制線條樣式
	                    color: 'auto'
	                }
	            },
	            pointer : {
	                width : 5
	            },
	            title : {
	                show : true,
	                offsetCenter: [0, '-40%'],       // x, y,單位px
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    fontWeight: 'bolder'
	                }
	            },
	            detail : {
	                formatter:'{value}℃',
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    color: 'auto',
	                    fontWeight: 'bolder'
	                }
	            },
	            data:[{value: tempArray, name: '溫度(℃)'}]//放置temp數據
	        }
	    ]
	};
	       
	  TempChart.setOption(option); 
 }
    /*二氧化碳數值圖表*/
    function CoGauge(ec) {
     // 基於準備好的dom,初始化echarts圖表
     var CoChart = ec.init(document.getElementById('co')); 
       
     var option = {
	    tooltip : {
	        formatter: "{a} <br/>{b} : {c}ppm"
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: true},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    series : [
	        {
	            name:'當前CO濃度值',
	            type:'gauge',
	            splitNumber: 10,       // 分割段數,默認爲5
	            axisLine: {            // 座標軸線
	                lineStyle: {       // 屬性lineStyle控制線條樣式
	                    color: [[0.2, '#228b22'],[0.8, '#48b'],[1, '#ff4500']], 
	                    width: 8
	                }
	            },
	            axisTick: {            // 座標軸小標記
	                splitNumber: 10,   // 每份split細分多少段
	                length :12,        // 屬性length控制線長
	                lineStyle: {       // 屬性lineStyle控制線條樣式
	                    color: 'auto'
	                }
	            },
	            axisLabel: {           // 座標軸文本標籤,詳見axis.axisLabel
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    color: 'auto'
	                }
	            },
	            splitLine: {           // 分隔線
	                show: true,        // 默認顯示,屬性show控制顯示與否
	                length :30,         // 屬性length控制線長
	                lineStyle: {       // 屬性lineStyle(詳見lineStyle)控制線條樣式
	                    color: 'auto'
	                }
	            },
	            pointer : {
	                width : 5
	            },
	            title : {
	                show : true,
	                offsetCenter: [0, '-40%'],       // x, y,單位px
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    fontWeight: 'bolder'
	                }
	            },
	            detail : {
	                formatter:'{value}ppm',
	                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
	                    color: 'auto',
	                    fontWeight: 'bolder'
	                }
	            },
	            data:[{value: coArray, name: 'CO(ppm)'}]//方式co數據
	        }
	   	  ]
		};
       
  		  CoChart.setOption(option); 
	}
 </script>


</body>
</html>


3、Struts.xml的配置

<!-- 數據監控 -->
         <action name="getData" class="getDataAction" method="getData"></action>

4、application,xml處的配置

<!-- 數據監控 -->
	<bean id="getDataAction" class="com.bs.view.action.DataAction" scope="prototype"></bean>


效果圖如下所示:


注:
關於實時刷新克採用java script計時回調方法

關於echarts的引入見此文:點擊打開鏈接

echarts可到百度官網下載:點擊打開鏈接

使用Json所需要的jar包:

點擊下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章