ECharts动态展示数据到条形图中
ECharts简单入门
Echarts官方文档
着重看 五分钟上手ECharts和 异步数据加载和更新这两栏
- 目标
- 学会在项目中引入ECharts
- 在网页上能成功展示一个ECharts图(就数据给定的那种)
- 大致了解下ECharts标签的意思
动态加载数据分析(以统计籍贯分布为例)
- dao层从数据库中取出数据
- service层调用(这里没什么业务逻辑)
- servlet拿到数据,封装为JSON格式发往前台
- JSP在前台拿到数据,在图表配置项中配置
dao层(使用MyBatis)
// model
public class LabNation {
private String nation;
private String num;
//...getter setter方法
}
// mapper
public interface LabUserMapper {
List<LabNation> countLabNation();
}
// xml
<select id="countLabNation" resultType="com.ychs.uol.model.LabNation">
SELECT nation, count(nation) num FROM labuser GROUP BY nation
</select>
// 调用
public List<LabNation> countLabNation(){
List<LabNation> list = new ArrayList<>();
SqlSession sqlSession = null;
try {
sqlSession = DBUtil.getSession();
LabUserMapper mapper = sqlSession.getMapper(LabUserMapper.class);
list = mapper.countLabNation();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeSession(sqlSession);
}
return list;
}
service层
public interface LabUserService {
List<LabNation> countLabNation();
}
public class LabUserServiceImpl implements LabUserService{
LabUserDao luDao = new LabUserDao();
@Override
public List<LabNation> countLabNation() {
return luDao.countLabNation();
}
}
servlet
@WebServlet("/CountNationServlet")
public class CountNationServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
LabUserService service = new LabUserServiceImpl();
List<LabNation> list = service.countLabNation();
String json = JSON.toJSONString(list);//FastJSON组件
response.getWriter().print(json);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
JSP
- 这个条形图很简陋了,其他的样式或者功能自行百度吧,应该资源很多
<div id="main" style="width: 600px;height:400px;float:left"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
$.getJSON("../CountNationServlet", function(data){
var nation = [];
var num = [];
for (var i = 0; i < data.length; i ++) {
nation[i] = data[i].nation;
num[i] = data[i].num;
}
bind(nation, num);// 绑定数据
});
function bind(nation, num){
var option = {
title: {
text: '实验室成员籍贯分布',
subtext:'数据来自labuser表'
},
legend: {
data:['籍贯信息']
},
/* toolbox最好加上,dataView这个在排错的时候挺好用的*/
toolbox: {
show :true,
feature : {
dataView : {show:true, readOnly:false},
magicType : {show:true, type: ['line','bar']},
restore : {show:true},
saveAsImage : {show:true}
}
},
/* X,Y轴中的type属性不能瞎起名,对应的data就是形参*/
xAxis: [
{
name: 'nation',
type:'category',
data: nation
}
],
yAxis: {},
series: [
{
name: 'number',
type: 'bar',
data: num
}
]
};
myChart.setOption(option);
};
</script>