溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Echarts+SpringMvc顯示后臺(tái)實(shí)時(shí)數(shù)據(jù)

發(fā)布時(shí)間:2020-10-24 06:21:42 來源:腳本之家 閱讀:155 作者:古柏樹下 欄目:編程語言

Echarts圖表數(shù)據(jù)一般都是從后臺(tái)數(shù)據(jù)庫實(shí)時(shí)取數(shù)據(jù)的 傳輸數(shù)據(jù)大多采用JSON數(shù)據(jù)格式
本文通過springmvc來攔截?cái)?shù)據(jù)請(qǐng)求 完成數(shù)據(jù)顯示

以下是工程目錄

 Echarts+SpringMvc顯示后臺(tái)實(shí)時(shí)數(shù)據(jù)

該工程在一個(gè)springmvc的基礎(chǔ)代碼上搭建 其中action類中只有ChartsAction有關(guān)
其中用到的包有 其中有部分沒用到的spring包 不影響使用
因?yàn)楸疚臅?huì)介紹兩種json傳輸辦法 jackjson和fastjson 所有兩種的包都有插入

Echarts+SpringMvc顯示后臺(tái)實(shí)時(shí)數(shù)據(jù)

1. 新建項(xiàng)目 導(dǎo)入所需jar包
2. 新建顯示界面html文件 zhuxing.html

在此工程中采用封裝函數(shù)填充的方式建立圖表
將option封裝成獨(dú)立函數(shù) div當(dāng)做容器 可以根據(jù)注入的option改變表格

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/echarts-all.js"></script>
<script src="js/macarons.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/getbar.js"></script>
</head>
<body>
 <div id="main" ></div>
 <script type="text/javascript">
  //初始化表格
  var myChart = echarts.init(document.getElementById('main'), 'macarons');
  //載入option配置
  myChart.setOption(getlinebar());
 </script>
</body>
</html>

3.新建所需數(shù)據(jù)庫 注入所需數(shù)據(jù)

這是不同瀏覽器在市場的占比

Echarts+SpringMvc顯示后臺(tái)實(shí)時(shí)數(shù)據(jù)

4.配置springmvc

echarts采用ajax請(qǐng)求獲取json數(shù)據(jù) 通過springmvc進(jìn)行攔截
首先在web.xml加入servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 id="WebApp_ID" version="3.1">

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spmvc-servlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <!-- 讓Spring MVC的前端控制器攔截帶有.do的請(qǐng)求 -->
 <!-- 注意這里不能攔截使用‘/'攔截所有請(qǐng)求 會(huì)導(dǎo)致js等靜態(tài)文件無法加載 -->
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
</web-app> 

需要特別注意 *.do 可以解決靜態(tài)資源無法加載的情況 總共有三種方法解決
接下來新建spmvc-servlet.xml來配置 這是使用Jackjson的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation=" 
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd  
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 <!-- spring可以自動(dòng)去掃描base-pack下面的包或者子包下面的java文件 -->
 <context:component-scan base-package="com.l.action" />
 <mvc:default-servlet-handler />
 <!-- 啟動(dòng)Springmvc注解驅(qū)動(dòng) -->
 <mvc:annotation-driven />

 <bean id="stringConverter"
  class="org.springframework.http.converter.StringHttpMessageConverter">
  <property name="supportedMediaTypes">
   <list>
    <value>text/plain;charset=UTF-8</value>
   </list>
  </property>
 </bean>
 <bean id="jsonConverter"
  class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
 <bean
  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
   <list>
    <ref bean="stringConverter" />
    <ref bean="jsonConverter" />
   </list>
  </property>
 </bean>
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>
</beans> 

5.數(shù)據(jù)庫連接以及數(shù)據(jù)獲取

因?yàn)橐獜臄?shù)據(jù)庫取數(shù)據(jù) 新建com.l.utils.DbUtil.java 來獲取數(shù)據(jù)連接

package com.l.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtil {
 /*
  * private String dbUrl = "jdbc:mysql://localhost:3306/test"; private String
  * dbUserName = "root"; private String dbPassword = "1234"; private String
  * jdbcName = "com.mysql.jdbc.Driver";
  */

 public Connection getcon() {
  try {
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");
   System.out.println("success");
   return con;
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }

 }

 public void close(Connection con, Statement sm, ResultSet rs) {
  try {
   // 關(guān)閉。后面獲取的對(duì)象先關(guān)閉。
   if (rs != null)
    rs.close();
   if (sm != null)
    sm.close();
   if (con != null)
    con.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

根據(jù)需要掃描的包 新建目錄 com.l.action.ChartsAction.java 使用注解@ResponseBody

package com.l.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.l.utils.DbUtil;

@Controller
public class ChartsAction {

 @RequestMapping(value = "/hello", method = RequestMethod.GET)
 @ResponseBody
 public List<Map<String, Object>> getbar() {
  Connection con = null;
  String sql = null;
  DbUtil dbutil = new DbUtil();
  try {
   con = dbutil.getcon();
   java.sql.Statement st = con.createStatement();
   sql = "select * from data";
   ResultSet rs = st.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) + " " + rs.getString(4));
    Map<String, Object> map = new HashMap<String, Object>();

    map.put("name", rs.getString(2));
    map.put("value", Double.parseDouble(rs.getString(3)));
    map.put("drilldown", Double.parseDouble(rs.getString(4)));
    list.add(map);
   }
   return list;
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
}

在地址欄數(shù)據(jù)http://localhost:8080/Demo01/hello.do來測試是否能夠顯示傳出的json數(shù)據(jù)

6.開始編寫option

當(dāng)請(qǐng)求可以收到j(luò)son數(shù)據(jù)后 新建js目錄,在該目錄下新建getbar.js
其中data設(shè)置最重要

function getlinebar(params) {
 option = {
  tooltip : {
   trigger : 'axis',
  },
  legend : {
   data : [ '最大占比', '最小占比' ]
  },
  toolbox : {
   show : true,
   orient : 'vertical',
   y : 'center',
   feature : {
    mark : {
     show : true
    },
    magicType : {
     show : true,
     type : [ 'line', 'bar' ]
    },
    dataView : {
     show : true,
     readOnly : false
    },
    restore : {
     show : true
    },
    saveAsImage : {
     show : true
    }
   }
  },
  calculable : true,
  xAxis : [ {
   type : 'category',
   data : (function() {
    var data = [];
    $.ajax({
     url : 'http://localhost:8080/Demo01/hello.do',
     type : 'get',
     async : false,
     dataType : "json",
     success : function(json) {
      if (json) {
       for (var i = 0; i < json.length; i++) {
        console.log(json[i].name);
        data.push(json[i].name);
       }
      }
     }
    })
    return data;
   })()
  } ],
  yAxis : [ {
   type : 'value',
   axisLabel : {
    formatter : '{value} %'
   }
  } ],

  series : [ {
   name : '最小占比',
   type : 'bar',
   data : (function() {
    var arr = [];
    $.ajax({
     url : 'http://localhost:8080/Demo01/hello.do',
     type : 'get',
     dataType : "json",
     async : false,
     success : function(data) {
      if (data) {
       for (var i = 0; i < data.length; i++) {
        console.log(data[i].drilldown);
        arr.push(data[i].drilldown);
       }
      }
     }
    })
    return arr;
   })()
  }, {
   name : '最大占比',
   type : 'bar',
   data : (function() {
    var arr = [];
    $.ajax({
     url : 'http://localhost:8080/Demo01/hello.do',
     type : 'get',
     dataType : "json",
     async : false,
     success : function(data) {
      if (data) {
       for (var i = 0; i < data.length; i++) {
        console.log(data[i].value);
        arr.push(data[i].value);
       }
      }
     }
    })
    return arr;
   })()
  } ]
 };
 return option;
}

最終顯示成功 數(shù)據(jù)返回正常

在自己編寫過程中遇到的問題主要有js html文件無法顯示的問題 **主要是springmvc攔截沒有設(shè)置正確
還有引入js文件的路徑問題也會(huì)導(dǎo)致js無法引入**

<script src="js/getbar.js"></script>

這樣的形式 注意不要再最前面加上/ 會(huì)導(dǎo)致請(qǐng)求錯(cuò)誤

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI