这是工程所有文件的一个目录
工程文件目录
我做了一个柱状图,一个饼状图,一个折线图,配置过程很恶心,出了好多错,所以在这里记录一下。
如果想直接看 echarts 的部分,可以跳过下面数据库的建立。
数据库的建立与获取数据
首先是建立数据库
数据库表结构这里主要用 bistu 数据库下面的 goods 这个表,这是一个商品表,有 商品编号, 商品名称, 商品价格, 商品销量, 商品库存, 商品详情。
然后导入 jar 包,这里我用了 C3P0 连接池 还有 DButils 来操作数据库, 此外还使用了 jstl 标签。
导入的jar包先来配置 C3P0 连接池,我们在 src 目录下新建一个 c3p0-config.xml 配置文件。
<?xml version="1.0" encoding="ISO-8859-1"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/bistu?useSSL=false&useUnicode=true&characterEncoding=utf8</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
然后在 util 包下写一个读取配置文件的功能类 ReadDataSource.java
package util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
/**
* Created by teaGod on 2017/9/19.
*/
public class ReadDataSource {
public static DataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
}
public static DataSource getDataSource(){
return dataSource;
}
}
接下来创建我们的实体类,在 entity 包下创建 Goods.java
package entity;
/**
* Created by teaGod on 2017/9/25.
*/
public class Goods {
private int id;
private String name;
private double price;
private int sales;
private int stock;
private String detail;
public Goods() {
}
public Goods(String name, double price, int sales, int stock, String detail) {
this.name = name;
this.price = price;
this.sales = sales;
this.stock = stock;
this.detail = detail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", sales=" + sales +
", stock=" + stock +
", detail='" + detail + '\'' +
'}';
}
}
然后是写 dao 层,dao 层里只写了一个简单的查询所有商品的方法。
GoodsDao.java:
package dao;
import entity.Goods;
import entity.StuBistu;
import java.sql.SQLException;
import java.util.List;
/**
* Created by teaGod on 2017/9/18.
*/
public interface GoodsDao {
List<Goods> queryAllGoods() throws SQLException;
}
GoodsDaoimpl.java
package dao;
import entity.Goods;
import entity.StuBistu;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import util.ReadDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
/**
* Created by teaGod on 2017/9/18.
*/
public class GoodsDaoImpl implements GoodsDao {
DataSource dataSource = ReadDataSource.getDataSource();
@Override
public List<Goods> queryAllGoods() throws SQLException {
QueryRunner queryRunner = new QueryRunner(dataSource);
String sql = "select * from goods";
return queryRunner.query(sql, new BeanListHandler<>(Goods.class));
}
}
现在可以先写一个测试类,看看数据库是否连接成功
DButilC3P0Test.java
import dao.GoodsDao;
import dao.GoodsDaoImpl;
import entity.Goods;
import java.sql.SQLException;
/**
* Created by teaGod on 2017/9/19.
*/
public class DButilC3P0Test {
public static void main(String[] args) {
GoodsDao goodsDao = new GoodsDaoImpl();
try {
for (Goods goods :
goodsDao.queryAllGoods()) {
System.out.println(goods);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
下面是控制台打印的结果,说明数据库连接成功
测试结果
Echart可视化
去 ECharts 官网下载 echarts.js
http://echarts.baidu.com/download.html下载后在 web 目录下新建一个 resource 文件夹, 将 echarts.js 拷贝进去。
然后是写我们的servlet,我们用它来实现数据的提取,并发送到前端 jsp 进行显示。
ServletQueryAllGoods.java:
package servlet;
import dao.GoodsDao;
import dao.GoodsDaoImpl;
import entity.Goods;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
/**
* Created by teaGod on 2017/9/25.
*/
@WebServlet(name = "ServletQueryAllGoods", value = "/ServletQueryAllGoods")
public class ServletQueryAllGoods extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GoodsDao goodsDao = new GoodsDaoImpl();
List<Goods> goodsList;
try {
goodsList = goodsDao.queryAllGoods();
request.setAttribute("goodsList", goodsList);
request.getRequestDispatcher("/zhu.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
前面的铺垫都已经完成,接下来是最关键的部分,开始利用 ECharts 进行数据可视化,这里我们都是在ECharts 官方实例的基础上进行了一些修改,从而实现统计数据库中商品的销量。
- 柱状图 zhu.jsp
<%--
Created by IntelliJ IDEA.
User: teaGod
Date: 2017/9/25
Time: 10:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>ECharts</title>
<meta charset="utf-8">
<!-- 引入 ECharts 文件 -->
<script src="${pageContext.request.contextPath}/resource/echarts.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
var arr = new Array();
var index = 0;
<c:forEach items="${goodsList}" var="goods">
arr[index++] = ${goods.sales};
</c:forEach>
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {
show: true
},
legend: {
data:['销量']
},
xAxis : [
{
type : 'category',
data : [
<c:forEach items="${goodsList}" var="g">
["${g.name}"],
</c:forEach>
]
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'销量',
type:'bar',
data: arr
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
结果:
柱状图- 饼状图 bing.jsp
<%--
Created by IntelliJ IDEA.
User: teaGod
Date: 2017/9/25
Time: 14:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>ECharts</title>
<meta charset="utf-8">
<!-- 引入 ECharts 文件 -->
<script src="${pageContext.request.contextPath}/resource/echarts.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
option = {
title : {
text: '超市商品销售统计',
subtext: '纯属虚构',
x:'center'
},
tooltip : {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
data: [
<c:forEach items="${goodsList}" var="g">
["${g.name}"],
</c:forEach>
]
},
series : [
{
name: '销售数量',
type: 'pie',
radius : '55%',
center: ['50%', '60%'],
data:[
<c:forEach items="${goodsList}" var="goods">
{value:"${goods.sales}", name:"${goods.name}"},
</c:forEach>
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
结果:
饼状图- 折线图 zhe.jsp
<%--
Created by IntelliJ IDEA.
User: teaGod
Date: 2017/9/25
Time: 15:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>ECharts</title>
<meta charset="utf-8">
<!-- 引入 ECharts 文件 -->
<script src="${pageContext.request.contextPath}/resource/echarts.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
var sale = new Array;
var index = 0;
<c:forEach items="${goodsList}" var="goods">
sale[index++] = ${goods.sales};
</c:forEach>
option = {
tooltip: {
trigger: 'axis',
position: function (pt) {
return [pt[0], '10%'];
}
},
title: {
left: 'center',
text: '超市商品销量图',
},
toolbox: {
feature: {
dataZoom: {
yAxisIndex: 'none'
},
restore: {},
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: [
<c:forEach items="${goodsList}" var="g">
["${g.name}"],
</c:forEach>
]
},
yAxis: {
type: 'value',
boundaryGap: [0, '100%']
},
dataZoom: [{
type: 'inside',
start: 0,
end: 10
}, {
start: 0,
end: 10,
handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
handleSize: '80%',
handleStyle: {
color: '#fff',
shadowBlur: 3,
shadowColor: 'rgba(0, 0, 0, 0.6)',
shadowOffsetX: 2,
shadowOffsetY: 2
}
}],
series: [
{
name:'商品销量',
type:'line',
smooth:true,
symbol: 'none',
sampling: 'average',
itemStyle: {
normal: {
color: 'rgb(255, 70, 131)'
}
},
areaStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgb(255, 158, 68)'
}, {
offset: 1,
color: 'rgb(255, 70, 131)'
}])
}
},
data: sale
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
结果:
折线图三种图最后都得到了,其实不同的图只是 option 中的代码不一样,我们在导入了官方的模板后,想画什么图,就去官方的实例里拷贝相应的 option 就好了。
最难的地方就是 option 中的数据格式化部分,从 servlet 拿到数据后,结合 jstl 表达式,格式化到 ECharts 中。我花的最多的时间就是在这上面,注意空格、逗号和括号这些小细节,否则调试起来保准让你疯掉。
最后,想要显示不同的图,记得修改 ServletQueryAllGoods.java 中的这行代码
request.getRequestDispatcher("/zhe.jsp").forward(request, response);
将 "/zhe.jsp" 修改成你想显示的。
网友评论