软件编程
位置:首页>> 软件编程>> java编程>> Echarts+SpringMvc显示后台实时数据

Echarts+SpringMvc显示后台实时数据

作者:古柏树下  发布时间:2021-06-08 03:38:42 

标签:Echarts,SpringMvc,显示数据

Echarts图表数据一般都是从后台数据库实时取数据的 传输数据大多采用JSON数据格式
本文通过springmvc来拦截数据请求 完成数据显示

以下是工程目录

 Echarts+SpringMvc显示后台实时数据

该工程在一个springmvc的基础代码上搭建 其中action类中只有ChartsAction有关
其中用到的包有 其中有部分没用到的spring包 不影响使用
因为本文会介绍两种json传输办法 jackjson和fastjson 所有两种的包都有插入

Echarts+SpringMvc显示后台实时数据

1. 新建项目 导入所需jar包
2. 新建显示界面html文件 zhuxing.html

在此工程中采用封装函数填充的方式建立图表
将option封装成独立函数 div当做容器 可以根据注入的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.新建所需数据库 注入所需数据

这是不同浏览器在市场的占比

Echarts+SpringMvc显示后台实时数据

4.配置springmvc

echarts采用ajax请求获取json数据 通过springmvc进行拦截
首先在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的请求 -->
<!-- 注意这里不能拦截使用‘/'拦截所有请求 会导致js等静态文件无法加载 -->
<servlet-mapping>
 <servlet-name>springmvc</servlet-name>
 <url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

需要特别注意 *.do 可以解决静态资源无法加载的情况 总共有三种方法解决
接下来新建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注解驱动 -->
<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.数据库连接以及数据获取

因为要从数据库取数据 新建com.l.utils.DbUtil.java 来获取数据连接


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 {
  // 关闭。后面获取的对象先关闭。
  if (rs != null)
   rs.close();
  if (sm != null)
   sm.close();
  if (con != null)
   con.close();
 } catch (Exception e) {
  e.printStackTrace();
 }
}

}

根据需要扫描的包 新建目录 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;
}
}

在地址栏数据http://localhost:8080/Demo01/hello.do来测试是否能够显示传出的json数据

6.开始编写option

当请求可以收到json数据后 新建js目录,在该目录下新建getbar.js
其中data设置最重要


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;
}

最终显示成功 数据返回正常

在自己编写过程中遇到的问题主要有js html文件无法显示的问题 **主要是springmvc拦截没有设置正确
还有引入js文件的路径问题也会导致js无法引入**


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

这样的形式 注意不要再最前面加上/ 会导致请求错误

来源:https://blog.csdn.net/sinat_29774479/article/details/74537451

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com