在经过数据可视化学习之后,我就在想我以前做过的项目中要求实现数据可视化。当时候很菜。只想到了用struts中的chart来画。没有做到像Echarts那么实现动态交互。在经过自己推磨与上网搜索之后,终于迎来了自己的第一个与后台交互的动态可视化界面。
在本节课学习中,我们需要用到Json的jar包与Struts2的jar包(自取)
资源路径:https://pan.baidu.com/s/1j5Kl5JSPhsiAOfa9Ba_ehw 提取码: zenn
一、前端界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html style="height:100%">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="js/echarts3/echarts.common.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.js"></script>
</head>
<body style="height:100%;margin:0">
<div id="main" style="width: 600px; height: 400px;">asdasdasd</div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
$(function(){
//页面加载函数就会执行
//页面加载异步查询字典数据
$.post("${pageContext.request.contextPath }/test_find.action",{},function(data){
//遍历json的数据
salesVolume = data.salesVolume;//销量
bussinessVolume = data.bussinessVolume;//营业额
months = data.months;//月份
// 3.配置option
var option = {
title : {
text : 'ECharts 入门示例'
},
tooltip : {},
legend : {
data : [ '销量' ],
data : [ '营业额' ]
},
xAxis : {
data : months
},
yAxis : {},
series : [ {
name : '销量',
type : 'bar',
data : salesVolume
}, {
name : '营业额',
type : 'line',
data : bussinessVolume
} ],
toolbox : {
show : true,
feature : {
mark : {
show : true
},
dataView : {
show : true,
readOnly : false
},
magicType : {
show : true,
type : [ 'line', 'bar' ]
},
restore : {
show : true
},
saveAsImage : {
show : true
}
}
}
}
myChart.setOption(option);
},"json")
});
</script>
</body>
</html>
二、Action界面代码
public String find() throws IOException {
Integer[] salesVolume = {10,100,20,56,35,80};
double[] bussinessVolume = {10*10,100*8.5,20*9.5,56*9,35*9.5,80*9};
String[] months = {"1","2","3","4","5","6"};
Map<String, Object> map = new HashMap<>();
map.put("salesVolume", salesVolume);
map.put("bussinessVolume",bussinessVolume);
map.put("months", months);
JSONObject jsonObject = JSONObject.fromObject(map);
ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
System.out.println(jsonObject.toString());
ServletActionContext.getResponse().getWriter().println(jsonObject.toString());
return null;
}
三、Struts.xml
<package name="crm" namespace="/" extends="struts-default">
<action name="test_*" class="Action.TestAction" method="{1}">
<result name="ok">NewFile.jsp</result>
<result name="success">NewFile.jsp</result>
</action>
</package>
四、注意点
1:在写Action的时候注意要返回null
2:在进行跳转的时候一定要把路径写对
3:在视图显示不出来的时候不要着急,看看自己是js没有导入,还是xml文件没有配置对。