Echarts-echart和springMVC实现堆栈图(读取JSON文件数据)

原创 2015年07月07日 16:23:00

这篇echarts的堆栈图主要是根据这篇D3.js堆栈图(http://blog.csdn.net/u013147600/article/details/46770415 )实现的。

效果图:




1.JSON文件数据:

{
	"name":"某市2005-1010年利润情况",
	"product":
	[
		{ "name": "PC" , 
		  "sales": [	{ "year":"2005", "profit": 3000 },
				{ "year":"2006", "profit": 1300 },
				{ "year":"2007", "profit": 3700 },
				{ "year":"2008", "profit": 4900 },
				{ "year":"2009", "profit": 700 },
				{ "year":"2010", "profit": 700 }] },
		{ "name": "SmartPhone" , 
		  "sales": [	{ "year":"2005", "profit": 2000 },
				{ "year":"2006", "profit": 4000 },
				{ "year":"2007", "profit": 1810 },
				{ "year":"2008", "profit": 6540 },
				{ "year":"2009", "profit": 2820 },
				{ "year":"2010", "profit": 1000 }] },
		{ "name": "Software" , 
		  "sales": [	{ "year":"2005", "profit": 1100 },
				{ "year":"2006", "profit": 1700 },
				{ "year":"2007", "profit": 1680 },
				{ "year":"2008", "profit": 4000 },
				{ "year":"2009", "profit": 4900 },
				{ "year":"2010", "profit": 700 }] }
	]

}


2.根据JSON文件新建的实例类

Domain.java

package com.entity;

/**
 * @author lyx
 *	
 * 2015-7-7上午11:09:19
 *
 *springechart.com.entity.Product
 */
public class Domain {

	private String name;
	private Product product;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	
	
	
}

Product.java
package com.entity;

/**
 * @author lyx
 *	
 * 2015-7-7上午11:10:11
 *
 *springechart.com.entity.Sales
 */
public class Product {

	private String name;
	
	private Sales sale;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Sales getSale() {
		return sale;
	}

	public void setSale(Sales sale) {
		this.sale = sale;
	}
	
}
Sales.java

package com.entity;

/**
 * @author lyx
 *	
 * 2015-7-7下午2:10:54
 *
 *springechart.com.entity.Profit
 */
public class Sales {

	private String year;
	private int profit;
	
	
	public String getYear() {
		return year;
	}
	public void setYear(String year) {
		this.year = year;
	}
	public int getProfit() {
		return profit;
	}
	public void setProfit(int profit) {
		this.profit = profit;
	}
	
	
}

2.服务层代码:

EchartsT.java

package com.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entity.China;
import com.entity.Domain;
import com.entity.Sales;
import com.entity.Provinces;
import com.entity.Product;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.LineType;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.MarkType;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.PointerType;
import com.github.abel533.echarts.code.SelectedMode;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.code.Y;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.data.PointData;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Funnel;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Map;
import com.github.abel533.echarts.series.MapLocation;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.LineStyle;
import com.google.gson.JsonArray;

/**
 * @author lyx
 *	
 * 2015-6-12下午1,34,50
 *
 *springechart.com.service.EchartsT
 */
public class EchartsT {
   
    /**
     * 读取json文件
     */
    public String jsonRead(String fullFileName)
    {
    	
        File file = new File(fullFileName);
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
 
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block  
        		System.out.println(e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
         //返回字符串
        return buffer.toString();
    }
    
    
    /**
     * @return
     * 堆栈图
     */
    public Option stackYear()
    {
    	//Json文件所在的路径
    	String fullFileName="E:/java/java code/Project/springechart/WebRoot/year.json";
    	
    	//调用读取文件函数
    	String data = jsonRead(fullFileName);
    	
    	//把字符串转换成Json对象
    	JSONObject obj =JSON.parseObject(data);
    	//提取json文件里面"product"对应的数组并保存为Json数组
    	JSONArray proArr = obj.getJSONArray("product");
    	
    	//获取用例说明名称
    	String legendName[] = new String[proArr.size()];
    	for (int i = 0; i < proArr.size(); i++) {
    		//根据"name"获得JOSN数组中的名称
    		legendName[i]=proArr.getJSONObject(i).getString("name");
		}
    	
    	//PC数据
    	//根据"sales"获得JOSN数组
    	JSONArray pcArr =JSON.parseArray(proArr.getJSONObject(0).getString("sales").toString());
    	//把JSON数组保存为List列表
    	List<Sales> pcList = JSON.parseArray(pcArr.toString(), Sales.class);
    	//计算列表大小
    	int length =pcList.size();
    	//保存 年份数组
    	String[] pcYear =new String[length];
    	//保存 利润数组
    	int[] pcProfit = new int[length];
    	//获得数据 保存在数组中
    	for (int i = 0; i <length; i++) {
			pcYear[i]=pcList.get(i).getYear();
			pcProfit[i]=pcList.get(i).getProfit();
		}
    		
    	//SmartPhone数据
    	JSONArray spArr =JSON.parseArray(proArr.getJSONObject(1).getString("sales").toString());
    	List<Sales> spList =JSON.parseArray(spArr.toString(), Sales.class);
    	
    	String[] spYear =new String[length];
    	int[] spProfit = new int[length];
    	
    	for (int i = 0; i <length; i++) {
			spYear[i]=spList.get(i).getYear();
			spProfit[i]=spList.get(i).getProfit();
		}
    	
    	//Software数据
    	JSONArray swArr = JSON.parseArray(proArr.getJSONObject(2).getString("sales").toString());
    	List<Sales> swList =JSON.parseArray(swArr.toString(), Sales.class);
    	
    	String[] swYear =new String[length];
    	int[] swProfit = new int[length];
    	
    	for (int i = 0; i <length; i++) {
			swYear[i]=swList.get(i).getYear();
			swProfit[i]=swList.get(i).getProfit();
		}
    		
    	//定义Option对象
    	Option option = new Option();  	
    	//标题栏
    	option.title(obj.getString("name"),"纯属虚构");
    	option.title().x(X.center);
    	//提示框
    	option.tooltip().trigger(Trigger.axis);
    	option.tooltip().axisPointer().type(PointerType.shadow);
    	//工具栏
    	option.toolbox().show(true).orient(Orient.vertical).x(X.right).y(Y.center).feature(Tool.mark,Tool.dataView,Tool.dataZoom,Tool.restore,Tool.saveAsImage,new MagicType(Magic.bar,Magic.line,
    			Magic.stack,Magic.tiled));
    	//用例说明
    	option.legend().data(legendName).orient(Orient.horizontal).x(X.right);
    	//可计算
    	option.calculable(true);
    	 //x轴-类目轴
    	option.xAxis(new CategoryAxis().data(
    			pcYear
    			
    			));
    	//y轴 - 值轴
    	option.yAxis(new ValueAxis());
    	
    	
    	//PC柱状体
    	Bar pcBar = new Bar(legendName[0]).stack("PC");
    	
    	/*bar.data(provinceProfit);*/ //返回的js代码中 data数据比需要的数据会多一对中括号,取不到数据,导致图形不能正常显示
    	//这里通过add()逐个添加数据
    	for (int i = 0; i < length; i++) {
			pcBar.data().add(pcProfit[i]);
		}
    	
    	//smartPhone柱状体
    	Bar spBar = new Bar(legendName[1]).stack("SmartPhone");
    	for (int i = 0; i < length; i++) {
    		spBar.data().add(spProfit[i]);
		}
    	
    	//software柱状体
    	Bar swBar = new Bar(legendName[2]).stack("Software");

    	for (int i = 0; i < length; i++) {
    		swBar.data().add(swProfit[i]);
		}
    	
    	//设置系列series
    	option.series(pcBar,spBar,swBar);
    	return option;
    	
    }
       
}


3.控制层代码:

echartsContr.java

package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.github.abel533.echarts.Option;
import com.service.EchartsT;

/**
 * @author lyx
 *	
 * 2015-6-12下午1:36:51
 *
 *springechart.com.controller.echartsContr
 */
@Controller
@RequestMapping("/echarts")
public class echartsContr {
	
	EchartsT ech = new EchartsT();

	/**
	 * @param res
	 * @return
	 * 堆栈图
	 */
	@RequestMapping("stackYear")
	public String stackYear(HttpServletRequest res)
	{
		//调用服务层的函数并保存返回值
				Option option=ech.stackYear();
				//通过json装换成字符串
				String opt =JSON.toJSONString(option);
				//将对象传入到jsp页面
				res.setAttribute("option", opt);
				
				return "/ec";	
	}

}

4.jsp页面代码:

ec.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>ECharts</title>
  <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
  </head>

<body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="height:400px"></div>

    <!-- ECharts单文件引入 -->
    <!--  <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>  --> 

 	 <script type="text/javascript" src="../js/echarts.js"></script> 
   
   <!-- <script type="text/javascript" src="js/echarts-all.js"></script> -->
    <script type="text/javascript">

    //路径配置
    	require.config({
    		paths:{
	    		 echarts: '../js'
	    		}
    	});
  
    	//获得后台传过来的JSON数据
    	var opt =${option};
    	//设置主要样式
    	require(
	    	[
	    		'echarts',	
	    		'echarts/chart/bar',
	    		'echarts/chart/line',
	    		'echarts/chart/pie',
	    		'echarts/chart/map',
	    		'echarts/chart/funnel'
	    	],
	    	function(ec){ 
	    		//初始化echart对象
	    		var chart =ec.init(document.getElementById('main'));

			   	chart.setOption(opt);
			   	
			  	 });
   
    </script>
</body>
</html>

5.运行成功后的页面源码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>ECharts</title>
  <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
  </head>

<body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="height:400px"></div>

    <!-- ECharts单文件引入 -->
    <!--  <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>  --> 

 	 <script type="text/javascript" src="../js/echarts.js"></script> 
   
   <!-- <script type="text/javascript" src="js/echarts-all.js"></script> -->
    <script type="text/javascript">

    //路径配置
    	require.config({
    		paths:{
	    		 echarts: '../js'
	    		}
    	});
  
    	//获得后台传过来的JSON数据
    	var opt ={"calculable":true,"legend":{"data":["PC","SmartPhone","Software"],"orient":"horizontal","x":"right"},"series":[{"data":[3000,1300,3700,4900,700,700],"name":"PC","stack":"PC","type":"bar"},{"data":[2000,4000,1810,6540,2820,1000],"name":"SmartPhone","stack":"SmartPhone","type":"bar"},{"data":[1100,1700,1680,4000,4900,700],"name":"Software","stack":"Software","type":"bar"}],"title":{"subtext":"纯属虚构","text":"某市2005-1010年利润情况","x":"center"},"toolbox":{"feature":{"mark":{"lineStyle":{"color":"#1e90ff","type":"dashed","width":2},"show":true,"title":{"mark":"辅助线开关","markClear":"清空辅助线","markUndo":"删除辅助线"}},"dataView":{"lang":["数据视图","关闭","刷新"],"readOnly":false,"show":true,"title":"数据视图"},"dataZoom":{"show":true,"title":{"dataZoom":"区域缩放","dataZoomReset":"区域缩放后退"}},"restore":{"show":true,"title":"还原"},"saveAsImage":{"lang":["点击保存"],"show":true,"title":"保存为图片","type":"png"},"magicType":{"show":true,"title":{"line":"折线图切换","stack":"堆积","bar":"柱形图切换","tiled":"平铺"},"type":["bar","line","stack","tiled"]}},"orient":"vertical","show":true,"x":"right","y":"center"},"tooltip":{"axisPointer":{"type":"shadow"},"trigger":"axis"},"xAxis":[{"data":["2005","2006","2007","2008","2009","2010"],"type":"category"}],"yAxis":[{"type":"value"}]};
    	//设置主要样式
    	require(
	    	[
	    		'echarts',	
	    		'echarts/chart/bar',
	    		'echarts/chart/line',
	    		'echarts/chart/pie',
	    		'echarts/chart/map',
	    		'echarts/chart/funnel'
	    	],
	    	function(ec){ 
	    		//初始化echart对象
	    		var chart =ec.init(document.getElementById('main'));//ec.init( $("#main"));

			   	chart.setOption(opt);
			   	
			  	 });
                      
   
   
    </script>
    
   
</body>
</html>

参考网站:http://git.oschina.net/free/ECharts

通过上面网站作者所编写的ECharts-2.2.4.jar ,导入到我们工程中这样我们的页面中的js代码,就可以现在项目的后台生成,并通过json转换成字符串传入到页面中,在jsp页面接收传入的json格式的字符串,后就可以生成我们设置的图表了。
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

eCharts添加自定义geojson数据实现地图展示

当初看到echarts的地图的时候感觉可以做点什么,但是一直米有实施,最近刚好用到了,就研究了研究,在echarts中添加了自定义的geojson数据,实现数据的地图展示。...

Echarts加载自定义地图geoJson

Echarts3提供的地图有时无法满足我们的需求,这时可以引入geoJson作为底图。

ECharts-Java使用Java快速开发ECharts图表

ECharts-Java类库地址:http://git.oschina.net/free/ECharts 百度ECharts地址:http://echarts.baidu.com/ 大概在5个月前的时...
  • isea533
  • isea533
  • 2015年01月28日 09:45
  • 96162

echart报表插件使用笔记(二)--按月统计

按月统计注册人数 java类: package com.spring.controller; import java.io.IOException; import java.sql.Connec...

echart饼图和折线图实例

require.config({     paths: {         echarts: 'js/echart'     } }); require(     [  ...

Echarts-echart和springMVC实现堆栈图(读取JSON文件数据)

Echarts-echart和springMVC实现堆栈图(读取JSON文件数据) 效果图: 1.JSON文件数据:   ? ...
  • bobo_93
  • bobo_93
  • 2016年08月18日 10:22
  • 721

基于Spring MVC的ECharts动态数据实时展示

Echarts

springboot的组装特性(依赖默认组装,有依赖就有组装)

springboot的组装特性(依赖默认组装,有依赖就有组装)   1,application在母包 2,依赖文件不能乱放,springboot会根据依赖默认配置好集成好,有配置文件的细化就会结...

Spring+SpringMVC+mybatis+easyui整合实例(三)spring mvc整合及mybatis事务部分

我们还是用一个例子来为这部分做个说明。完整的整合实例步骤请大家看我之前的博客。 另外剩下的部分我会每天进行更新,到最后完成一个完整的整合实例项目,大家可以跟着学习一下,有问题回复即可。一、首先添加框架...

spring 注入 动态注入

spring 注入: 1,配置文件注入      (一)bean            --> //这部分也是字符串注入    (二)字符串注入      ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Echarts-echart和springMVC实现堆栈图(读取JSON文件数据)
举报原因:
原因补充:

(最多只允许输入30个字)