本案例基于springmvc下Echart图表展示基础的折线图和柱状图。难点在于给图表的Series参数赋值:
1.导入echarts.js下载网站http://echarts.baidu.com/download.html
2.测试页面,直接访问查看是否能正常展示
index_base.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts图表(静态页面展示实例)</title>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/echarts.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 700px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
/* var option = {
title: {
text: '柱状图'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
}; */
var option = {
title: {
text: '折线图'
},
tooltip: {
trigger: 'axis'
},
legend: {
data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['2017-12-1','2017-12-2','周三','周四','周五','周六','周日','12-2','12-3']
},
yAxis: {
type: 'value'
},
series: [
{
name:'邮件营销',
type:'line',
stack: '总量',
itemStyle : { normal: {label : {show: true}}},
data:[120, 132, 101, 134, 90, 230, 210,220,220]
},
{
name:'联盟广告',
type:'line',
stack: '总量',
itemStyle : { normal: {label : {show: true}}},
data:[220, 182, 191, 234, 290, 330, 310,220,2201]
},
{
name:'视频广告',
type:'line',
stack: '总量',
itemStyle : { normal: {label : {show: true}}},
data:[150, 232, 201, 154, 190, 330, 410,220,220]
},
{
name:'直接访问',
type:'line',
stack: '总量',
itemStyle : { normal: {label : {show: true}}},
data:[320, 332, 301, 334, 390, 330, 320,420,220]
},
{
name:'搜索引擎',
type:'line',
stack: '总量',
itemStyle : { normal: {label : {show: true}}},
data:[820, 932, 901, 934, 1290, 1330, 1320,2203,2204]
}
]
};
// 使用刚指定的配置项和数据显示图表
myChart.setOption(option);
</script>
</body>
</html>
3.ajax交互动态获取
需要导入json包,Springmvc包,My97DatePicker日期控件,Echarts.js,jquery-1.9.1.min.js
3.1 页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts图表(动态ajax展示)</title>
<link href="http://libs.baidu.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/echarts.js"></script>
<script type="text/javascript" src="My97DatePicker/WdatePicker.js"></script>
</head>
<body>
<div style="margin-top:10px;">
<span style="font-size:20px;">开始时间:</span><input class="Wdate" type="text" onClick="WdatePicker()" id="start">—<span style="font-size:20px;">结束时间</span><input class="Wdate" type="text" onClick="WdatePicker()" id="end"><br/>
<span style="font-size:20px;">展示方式:</span>
<input name="chart" type="radio" value="1" checked="checked">折线图
<input name="chart" type="radio" value="2">柱状图
<button type="button" class="btn btn-primary" οnclick="jchart()">查看</button>
</div>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 700px;height:400px;"></div>
<script type="text/javascript">
//-------------------图表开始--------------------
function jchart(){
//获取参数
var startDate=$("#start").val();
var endDate=$("#end").val();
var chart=$("input[name=chart]:checked").val();
//基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
//图表显示加载样式
myChart.showLoading();
var options = {
title: {
text: "",
},
tooltip: {
trigger: 'axis'
},
legend: {
data: []
},
toolbox: {
show: true,
feature: {
mark: false
}
},
calculable: true,
label:{
normal:{
show: true,
position: 'inside'}
},
xAxis: [
{
/* axisLabel: {rotate: 90,}, */
type: 'category',
data: []
}
],
yAxis: [
{
type: 'value',
splitArea: { show: true }
}
],
series: []
};
//通过Ajax获取数据
$.ajax({
async : false, //同步执行
url : "<%=basePath%>count.htm",
data: {"startDate":startDate,"endDate":endDate,"chart":chart},
dataType : "json",
success:function(data) {
//将返回的category和series对象赋值给options对象内的category和series
//主体内容
options.series = data.series;
//头部动态选择
options.legend.data = data.legend;
//因为xAxis是一个数组 这里需要是xAxis[i]的形式,横坐标
options.xAxis[0].data = data.category;
myChart.hideLoading();
// 使用刚指定的配置项和数据显示图表
myChart.setOption(options);
},
error : function(errorMsg) {
alert("图表请求数据失败啦!");
}
})
}
</script>
</body>
</html>
3
.2 Controller
package com.bbaqw.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bbaqw.pojo.Series;
/**
*
* @author Administrator
*
*/
@Controller
@Scope("prototype")
public class CountController {
@RequestMapping("count")
public String countInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
JSONObject json=new JSONObject();
//2017-02-01-2017-02-23
String start=request.getParameter("startDate");
String end=request.getParameter("endDate");
int chart=Integer.parseInt(request.getParameter("chart"));
//1.分类赋值(横坐标)
List<String> category=new ArrayList<String>();
if(start!=null&&!"".equals(start)&&end!=null&&!"".equals(end)){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date dstart=sdf.parse(start);
Date dend=sdf.parse(end);
List<Date> listDate=getDatesBetweenTwoDate(dstart, dend);
/* 获取选中时间的集合()
* for(Date d:list){
System.out.println(d.toString());
}*/
for(int i=0;i<listDate.size();i++){
category.add(sdf.format(listDate.get(i)));
}
}
json.put("category", category);
//2.图例动态赋值
//2.1 List<String> legend=new ArrayList<String>(Arrays.asList(new String[] {"PC端","M端","总IP"}));
List<String> legend = Arrays.asList("pc端", "M端", "总IP");
/*2.2 List<String> legend=new ArrayList<String>();
legend.add("pc端");
legend.add("M端");
legend.add("总IP");*/
json.put("legend", legend);
//3.主要数据获取
List<Series> series = new ArrayList<Series>();
//---模拟开始:此处模拟数据库读取的三个Long类型集合
List<Long> serisData1=new ArrayList<Long>();
List<Long> serisData2=new ArrayList<Long>();
List<Long> serisData3=new ArrayList<Long>();
for(int i=1;i<6;i++){
serisData1.add((long)i);
}
for(int i=12;i<17;i++){
serisData2.add((long)i);
}
for(int i=18;i<23;i++){
serisData3.add((long)i);
}
//---模拟结束---
if(chart==1){
series.add(new Series("pc端", "line", serisData1));
series.add(new Series("M端", "line", serisData2));
series.add(new Series("总IP", "line", serisData3));
}else if(chart==2){
series.add(new Series("pc端", "bar", serisData1));
series.add(new Series("M端", "bar", serisData2));
series.add(new Series("总IP", "bar", serisData3));
}
json.put("series", series);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(json.toString());
return null;
}
/**
* 根据开始时间和结束时间返回时间段内的时间集合
*
* @param beginDate
* @param endDate
* @return List
*/
public List<Date> getDatesBetweenTwoDate(Date beginDate, Date endDate) {
List<Date> lDate = new ArrayList<Date>();
lDate.add(beginDate);// 把开始时间加入集合
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, 1);
// 测试此日期是否在指定日期之后
if (endDate.after(cal.getTime())) {
lDate.add(cal.getTime());
} else {
break;
}
}
lDate.add(endDate);// 把结束时间加入集合
return lDate;
}
}
3
.3 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
3.4 applicationContext.xml
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- spring扫描base-package下所有文件,扫描到@controller这些类就注册为bean -->
<context:component-scan base-package="com.bbaqw.controller"/>
<!-- 等同于注解处理器适配器和注解处理器映射器 -->
<mvc:annotation-driven/>
<!-- 返回处理跳转页面的前缀后缀,视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
</beans>
3.5 Series实体类
package com.bbaqw.pojo;
import java.util.List;
public class Series {
public String name;
public String type;
public List<Long> data;// 这里要用int 不能用String 不然前台显示不正常(特别是在做数学运算的时候)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Long> getData() {
return data;
}
public void setData(List<Long> data) {
this.data = data;
}
public Series(String name, String type, List<Long> data) {
this.name = name;
this.type = type;
this.data = data;
}
}