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

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

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" style="width: 1000px; height: 500px"></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ù)
這是不同瀏覽器在市場的占比

4.配置springmvc
echarts采用ajax請求獲取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的請求 --> <!-- 注意這里不能攔截使用‘/'攔截所有請求 會導(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可以自動去掃描base-pack下面的包或者子包下面的java文件 -->
<context:component-scan base-package="com.l.action" />
<mvc:default-servlet-handler />
<!-- 啟動Springmvc注解驅(qū)動 -->
<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)閉。后面獲取的對象先關(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)請求可以收到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文件的路徑問題也會導(dǎo)致js無法引入**
<script src="js/getbar.js"></script>
這樣的形式 注意不要再最前面加上/ 會導(dǎo)致請求錯誤
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java構(gòu)造器(構(gòu)造方法)與方法區(qū)別說明
這篇文章主要介紹了Java構(gòu)造器(構(gòu)造方法)與方法區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Spring中的事務(wù)管理及實(shí)現(xiàn)方式解析
這篇文章主要介紹了Spring中的事務(wù)管理及實(shí)現(xiàn)方式解析,Spring事務(wù)管理基于底層數(shù)據(jù)庫本身的事務(wù)處理機(jī)制,數(shù)據(jù)庫事務(wù)的基礎(chǔ),是掌握Spring事務(wù)管理的基礎(chǔ),這篇總結(jié)下Spring事務(wù),需要的朋友可以參考下2024-01-01
mybatis,foreach,找不到參數(shù)報(bào)錯問題及解決
這篇文章主要介紹了mybatis,foreach,找不到參數(shù)報(bào)錯問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

