首页 > 编程语言 >java-echart报表插件使用笔记

java-echart报表插件使用笔记

时间:2023-05-01 16:44:24浏览次数:45  
标签:插件 java echart mav json import echarts

java-echart报表插件使用笔记

 

 

报表插件Echart

 

java类

 

package com.spring.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

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

import net.sf.json.JSONArray;

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

@Controller
public class EchartController {
	
	/**
	 * 静态的Echart报表页面
	 */
	@RequestMapping(value="user/echart", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView PostJsonTest(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ModelAndView mav=new ModelAndView();
		mav.addObject("time", new Date());
		mav.setViewName("echart/echart");
		return mav;
	}
	
	/**
	 * 动态的Echart报表页面
	 */
	@RequestMapping(value="user/echart2", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView dynamicEchart(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ModelAndView mav=new ModelAndView();
		String str[]={"衬衫2","羊毛衫2","雪纺衫2","裤子2","高跟鞋2","袜子2","nickname"};
		float bar[]={15, 28, 41, 45, 56, 120, 89};
		
		List<String> category=Arrays.asList(str);//将数组转换成为list
		mav.addObject("time", new Date());
		mav.addObject("listData", category);//list
		mav.addObject("array", str);//数组
		
		mav.addObject("jsonArray", JSONArray.fromObject(str));//转换为json数组
		mav.addObject("jsonList", JSONArray.fromObject(category));//转换为json数组
		mav.addObject("jsonInt", JSONArray.fromObject(bar));//转换为json数组
		mav.setViewName("echart/dynamicEchart");
		return mav;
	}
	
	
}


静态页面:

 

 

<%@ 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>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'echart.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
	<script type="text/javascript" src="<%=basePath%>resources/echart/esl.js"></script>

  </head>
  
  <body>
    	<div id="main" style="height:400px"></div>
    
	    <script type="text/javascript">
	        // 路径配置
	        require.config({
	            paths:{ 
	                'echarts' : 'resources/echart/echarts',
	                'echarts/chart/bar' : 'resources/echart/echarts'
	            }
	        });
	        
	        // 使用
	        require(
	            [
	                'echarts',
	                'echarts/chart/bar' // 使用柱状图就载入bar模块,按需载入
	            ],
	            function (ec) {
	                // 基于准备好的dom,初始化echarts图表
	                var myChart = ec.init(document.getElementById('main')); 
	                
	                var option = {
	                    tooltip: {
	                        show: true
	                    },
	                    legend: {
	                        data:['销量']
	                    },
	                    xAxis : [
	                        {
	                            type : 'category',
	                            data : ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
	                        }
	                    ],
	                    yAxis : [
	                        {
	                            type : 'value'
	                        }
	                    ],
	                    series : [
	                        {
	                            "name":"销量",
	                            "type":"bar",
	                            "data":[5, 20, 40, 10, 10, 20]
	                        }
	                    ]
	                };
	        
	                // 为echarts对象载入数据 
	                myChart.setOption(option); 
	            }
	        );
	    </script>
  </body>
</html>

 

 

动态页面:

 

<%@ 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>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'dynamicEchart.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script src="<%=basePath%>js/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>resources/echart/esl.js"></script>
  </head>
  
  <body>
        	<div id="main" style="height:400px"></div>
            <input type="text" id="array" class="array" value="${array}" >
            <input type="text" id="listData" class="listData" value="${listData}" >
            <input type="text" id="jsonArray" class="jsonArray" value="${jsonArray}" >
            <input type="text" id="jsonList" class="jsonList" value="${jsonList}" >
            
	    <script type="text/javascript">
	        // 路径配置
	        require.config({
	            paths:{ 
	                'echarts' : 'resources/echart/echarts',
	                'echarts/chart/bar' : 'resources/echart/echarts'
	            }
	        });
	        
	        // 使用
	        require(
	            [
	                'echarts',
	                'echarts/chart/bar' // 使用柱状图就载入bar模块,按需载入
	            ],
	            function (ec) {
	                // 基于准备好的dom,初始化echarts图表
	                var myChart = ec.init(document.getElementById('main')); 
	                
	                var jsonList=${jsonList};//接收后台传过来的json数组
	                alert(jsonList);
	                var jsona=${jsonArray};//接收后台传过来的json数组
	                alert(jsona);
	                
	                var jsonInt=${jsonInt};//接收后台传过来的json数组
	                alert(jsonInt);
	                //便利json数组
	              /*   $.each(json,function(n,value) {
	                	alert(value)
	                }); */
	                
	                var option = {
	                    tooltip: {
	                        show: true
	                    },
	                    legend: {
	                        data:['销量']
	                    },
	                    xAxis : [
	                        {
	                            type : 'category',
	                            data : jsonList
	                        }
	                    ],
	                    yAxis : [
	                        {
	                            type : 'value'
	                        }
	                    ],
	                    series : [
	                        {
	                            "name":"销量",
	                            "type":"bar",
	                            "data":jsonInt
	                        }
	                    ]
	                };
	        
	                // 为echarts对象载入数据 
	                myChart.setOption(option); 
	            }
	        );
	    </script>
  </body>
</html>
       

(二)--按月统计

按月统计注冊人数

java类:

 

package com.spring.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class EchartController {

	/**
	 * Echart报表按月份统计
	 */
	@RequestMapping(value = "user/month", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView monthStatistics(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String year = ServletRequestUtils.getStringParameter(request, "year",
				"2014");
		ModelAndView mav = new ModelAndView();
		MySqlData mySqlData = new MySqlData();
		Map<Object, Object> map = new HashMap<Object, Object>();
		map = mySqlData.selectMonth(year);

		List<Integer> data = new ArrayList<Integer>();
		List<String> month = new ArrayList<String>();

		// 遍历map
		/*
		 * Iterator<Entry<Object, Object>> it = map.entrySet().iterator(); while
		 * (it.hasNext()) {
		 * 
		 * @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry)
		 * it.next(); String key = (String) entry.getKey(); Integer value =
		 * Integer.valueOf((String) entry.getValue());
		 * System.out.println("--------"+key); data.add(value);//数据
		 * month.add(key);//月份 }
		 */

		// 遍历2map
		for (Object m : map.keySet()) {
			Integer value = Integer.valueOf((String) map.get(m));
			System.out.println("--------" + m);
			data.add(value);// 数据
			month.add(m + "月");// 月份
		}

		mav.addObject("time", new Date());
		// mav.addObject("jsonMap",
		// JSONArray.fromObject(map));//将map转换为json数组//map转为json时map的key必须是string类型的
		mav.addObject("jsonData", JSONArray.fromObject(data));// 将list转换为json数组
		mav.addObject("jsonMonth", JSONArray.fromObject(month));// 将list转换为json数组
		mav.setViewName("echart/monthEchart");//
		return mav;
	}

	// ///////////////////////////////////////////////////////////////////////////////////////////////////////
	// /内部类
	class MySqlData {
		private String username;
		private String password;
		private Connection connection;
		private PreparedStatement ps;

		// //构造函数
		public MySqlData() {
			// TODO Auto-generated constructor stub

			String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
			String username = "root";
			String password = "";
			// 载入驱动程序以连接数据库
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(url, username,
						password);
			}
			// 捕获载入驱动程序异常
			catch (ClassNotFoundException cnfex) {
				System.err.println("装载 JDBC/ODBC 驱动程序失败");
				cnfex.printStackTrace();
			}
			// 捕获连接数据库异常
			catch (SQLException sqlex) {
				System.err.println("无法连接数据库");
				sqlex.printStackTrace();
			}

		}

		// 查询方法1
		/*
		 * select DATE_FORMAT(date_added,'%Y-%m') as month,count(*) as shumu
		 * from user where DATE_FORMAT(date_added,'%Y')=2014 group by month
		 * order by month;
		 */
		public Map<Object, Object> selectMonth(String year) {
			List<Object> maplist = new ArrayList<Object>();
			Map<Object, Object> map = new HashMap<Object, Object>();
			try {
				ps = connection
						.prepareStatement("select DATE_FORMAT(ptime,'%m') as month,count(*) as shumu from cc_user "
								+ " where DATE_FORMAT(ptime,'%Y')=? group by month order by month;");
				ps.setString(1, year);

				ResultSet rs = ps.executeQuery();
				while (rs.next()) {
					map.put(rs.getInt("month"), rs.getString("shumu"));
					System.out.println("月份:" + rs.getString("month") + "数目:"
							+ rs.getString("shumu"));
					maplist.add(map);
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return map;

		}

	}// 内部类

}// /echart类

页面:

 

 

<%@ 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>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'monthEchart.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script src="<%=basePath%>js/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>resources/echart/esl.js"></script>
  </head>
  
  <body>
       		<div id="main" style="height:400px"></div>
            
	    <script type="text/javascript">
	        // 路径配置
	        require.config({
	            paths:{ 
	                'echarts' : 'resources/echart/echarts',
	                'echarts/chart/bar' : 'resources/echart/echarts'
	            }
	        });
	        
	        // 使用
	        require(
	            [
	                'echarts',
	                'echarts/chart/bar' // 使用柱状图就载入bar模块,按需载入
	            ],
	            function (ec) {
	                // 基于准备好的dom。初始化echarts图表
	                var myChart = ec.init(document.getElementById('main')); 
	                
	                var jsonData=${jsonData};//接收后台传过来的json数组
	                alert(jsonData);
	                
	                var jsonMonth=${jsonMonth};
	                alert(jsonMonth);
	                
	                //便利json数组
	              /*   $.each(json,function(n,value) {
	                	alert(value)
	                }); */
	                
	                var option = {
	                    tooltip: {
	                        show: true
	                    },
	                    legend: {
	                        data:['注冊人数']
	                    },
	                    xAxis : [
	                        {
	                            type : 'category',
	                            data : ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",]
	                        }
	                    ],
	                    yAxis : [
	                        {
	                            type : 'value'
	                        }
	                    ],
	                    series : [
	                        {
	                            "name":"注冊人数",
	                            "type":"bar",
	                            itemStyle: {
	                                normal: {
	                                	//柱状图颜色
	                                    color: '#0080ff',
	                                    label: {
	                                         show: true,
	                                         //position : 'inside',
	                                         formatter : '{b}',
	                                         textStyle: {
	                                             color: '#10E922'
	                                         }
	                                     }
	                                }
	                            },
	                            "data":jsonData
	                        }
	                    ]
	                };
	        
	                // 为echarts对象载入数据 
	                myChart.setOption(option); 
	            }
	        );
	    </script>
  </body>
</html>
 

标签:插件,java,echart,mav,json,import,echarts
From: https://www.cnblogs.com/xinxihua/p/17366669.html

相关文章

  • JAVA创建线程的方式总结
    1.继承Thread类通过继承Thread类,并重写它的run方法,就可以创建一个线程。publicclassTestThread1extendsThread{publicTestThread1(Stringname){super(name);}@Overridepublicvoidrun(){System.out.println(Thread.currentTh......
  • java:输入一个字符串,在其中寻找长度最长的,不含重复字符的字符串,如果有多个长度相同的最
    publicclasstest2{publicstaticList<String>findLongestSubstring(Strings){List<String>result=newArrayList<>();intn=s.length();Map<Character,Integer>map=newHashMap<......
  • JavaSE大纲
    jdk8&9新特性Lambda表达式多线程IO流异常CollectionsListMapSet泛型可变参数Collection集合的使用StringBuffer&StringBuilder基本数据类型和字符串的相互转换装箱拆箱日期Arrays工具类&Object类静态内部类&字符串多态,构造方法接口继承封装抽象面向对象......
  • Java线程池中的四种拒绝策略
    CallerRunsPolicy:这是默认的拒绝策略,当线程池队列已满并且无法处理新任务时,将由提交任务的线程来执行该任务。这种策略可以降低新任务的流量,但也会增加提交任务的线程的负载。AbortPolicy:当线程池队列已满并且无法处理新任务时,将抛出RejectedExecutionException异常,阻止新任......
  • JAVA的Jdbc连接Access数据库
      Eclipse加入Access_JDBC30.jar:   程序如下:importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.Statement;publicclassconn{publicstaticStringconnct(){try{......
  • rabbitmq 延迟队列_Delayed Message 插件实现 RabbitMQ 延迟队列
    延迟队列是为了存放那些延迟执行的消息,待消息过期之后消费端从队列里拿出来执行。作者简介:五月君,NodejsDeveloper,慕课网认证作者,热爱技术、喜欢分享的90后青年,欢迎关注Nodejs技术栈(id:NodejsRoadmap)和Github开源项目 https://www.nodejs.redDLX+TTL方式存在的时序问......
  • 基于jQuery的FlexiGrid的插件使用和改造
    已不推荐下载,如要下载去这个连接下载最新的http://gundumw100.iteye.com/admin/blogs/545610上面的2个链接是我参考的例子虽然Flexigrid已然算是优秀,但是问题还是有?比如:1:不支持在列首添加checkbox列2:如何给行附加事件(如右键快显菜单或双击)或者在最后列添加操作列(在列的定......
  • Java内部类与匿名类
    内部类定义:一个类的内部又完整的嵌套了另一个类结构,被嵌套的类就被我们称为内部类,嵌套内部类的类被我们称为外部类//外部类classOuter{ //内部类 classInner { }}packageInnerclass;//外部其他类publicclassc1{}classOuter{//属性private......
  • java 基础(5)在idea中对java程序打包运行
    第一步 第二步 第三步  src目录下 第四步   第五步:  ......
  • Java层序遍历打印二叉树(有Null值)
    publicclassSolution{publicstaticvoidmain(String[]args){Integer[]arr={3,9,20,null,null,15};//根据数组构造出二叉树TreeNodetreeNode=creatTreeNode(arr,0);//层序有Null值的打印二叉树printBin......