JSP展示Echarts线形图,展示12个月份的数据
引入echarts-2.1.8/echarts.js
projectCountTrend.jsp:
<script>
//路径配置
require
.config({
paths : {
echarts : '${pageContext.request.contextPath}/skins/scripts/echarts-2.1.8'
}
});
// 使用
require([ 'echarts', 'echarts/chart/line' // 使用柱状图就加载line模块,按需加载
]);
$(function() {
drawLine();
});
/**
* 显示折线图
*/
function drawLine() {
$.post(GLOBAL_PATH
+ '/cnitsecStatisticsCount!retrieveCountLineChart.sbr',
SerializeObject($("#searchIdforu")), function(data) {
var option = {
title : {
x : 'center',
text : '项目数量同比分析',
subtext : '项目数量按月份同比分析',
},
tooltip : {
trigger : "item",
formatter : "{a} <br/>{b} : {c}"
},
legend : {
x : 'right',
data : data.legends
},
xAxis : [ {
type : "category",
name : "x",
boundaryGap : false,
splitLine : {
show : false
},
data : data.xAxis
} ],
yAxis : [ {
type : "log",
name : "y"
} ],
series : data.series
};
// 为echarts对象加载数据
require("echarts").init(
document.getElementById('systemChartforu'))
.setOption(option);
}, "json");
}
</script>
html:
<div class="easyui-layout" fit="true">
<div data-options="region:'north',border:false">
<div id="userSelect" style="padding:5px;height:40px;">
<form id="searchIdforu" method="post">
</form>
</div>
</div>
<div data-options="region:'center',border:false">
<table class="table">
<tr>
<td>
<div class="images" id="systemChartforu" style="height:380px" >
</div>
</td>
</tr>
</table>
</div>
</div>
Java Action层:
package com.sbr.cnitsec.query.action;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.sbr.cnitsec.emanage.model.CnitsecEManage;
import com.sbr.cnitsec.emanage.service.ICnitsecEManageService;
import com.sbr.platform.exception.SBRBusinessException;
import com.sbr.sdp.platform.common.action.BaseAction;
@Action(value="cnitsecStatisticsCount",results = {
@Result(name = "page", location = "/jsp/cnitsec/query/projectCountTrend.jsp"),
})
public class CnitsecStatisticsCountAction extends BaseAction {
private static final long serialVersionUID = 1L;
@Resource
ICnitsecEManageService cnitsecEManageService;
private String orgIds;//组织机构查询条件
private String year;//年度 按年度统计项目数
private CnitsecEManage cnitsecEManage = new CnitsecEManage();
/**
* 跳转到项目数量同比分析页面
* @return
*/
public String prePage() {
return BaseAction.ACTION_RESULT_PAGE;
}
/**
* @Title retrieveCountLineChart
* @Description 获取项目数量同比分析折线图数据
*/
public void retrieveCountLineChart(){
try{
String orgIdStr = "";
if (orgIds != null && !"".equals(orgIds)) {
String[] orgs = orgIds.split(",");
for (String orgId : orgs) {
orgIdStr += "'" + orgId + "',";
}
if (orgIdStr != null && !"".equals(orgIdStr)) {
orgIdStr = orgIdStr.substring(0, orgIdStr.length() - 1);
}
}
Map map = cnitsecEManageService.retrieveCountLineData(orgIdStr, year);
writeJson(map);
}catch(Exception e){
new SBRBusinessException();
}
}
@Override
public Object getModel() {
return cnitsecEManage;
}
public CnitsecEManage getCnitsecEManage() {
return cnitsecEManage;
}
public void setCnitsecEManage(CnitsecEManage cnitsecEManage) {
this.cnitsecEManage = cnitsecEManage;
}
public String getOrgIds() {
return orgIds;
}
public void setOrgIds(String orgIds) {
this.orgIds = orgIds;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
writeJson(map) 使用fastjson工具类
Java serviceImpl层:
@SuppressWarnings("rawtypes")
@Override
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
public Map retrieveCountLineData(String orgIds, String year){
// 柱状图的map数据
Map lineMap = new HashMap();
// x轴要显示的月份
List<String> months = new ArrayList<String>();
for (int i = 1; i <= 12; i++) {
months.add(String.valueOf(i) + "月");
}
//右上角显示的单位
List<String> years = new ArrayList<String>();
// 获取当前年份
Calendar calendar = Calendar.getInstance();
int tyear = calendar.get(Calendar.YEAR);
if (year != null && !year.equals("")) {
tyear = Integer.valueOf(year);
} else {
tyear = calendar.get(Calendar.YEAR);
}
for (int i = tyear; i >= (tyear-1); i--) {
years.add(String.valueOf(i)+"年");
}
List<Map> projectNumByMonth = new ArrayList<Map>();
// 统计今年度12个月的项目数
List<Object[]> tyearListData = new ArrayList<Object[]>();
List<Object[]> lyearListData = new ArrayList<Object[]>();
String tsql = "", lsql = "";
if(null != orgIds && !"".equals(orgIds)){
tsql = "select o.name, DATE_FORMAT(m.contract_signing_time,'%m') months,count(m.id) count from cnitsec_e_manage m RIGHT JOIN sys_organization o ON m.org_id = o.id WHERE m.contract_signing_time >= '"+tyear+"' AND m.contract_signing_time <= '"+(tyear+1)+"' AND m.org_id in ( "+orgIds+" ) group by months";
lsql = "select o.name, DATE_FORMAT(m.contract_signing_time,'%m') months,count(m.id) count from cnitsec_e_manage m RIGHT JOIN sys_organization o ON m.org_id = o.id WHERE m.contract_signing_time >= '"+(tyear-1)+"' AND m.contract_signing_time <= '"+tyear+"' AND m.org_id in ( "+orgIds+" ) group by months";
}else{
tsql = "select o.name, DATE_FORMAT(m.contract_signing_time,'%m') months,count(m.id) count from cnitsec_e_manage m RIGHT JOIN sys_organization o ON m.org_id = o.id WHERE m.contract_signing_time >= '"+tyear+"' AND m.contract_signing_time <= '"+(tyear+1)+"' group by months";
lsql = "select o.name, DATE_FORMAT(m.contract_signing_time,'%m') months,count(m.id) count from cnitsec_e_manage m RIGHT JOIN sys_organization o ON m.org_id = o.id WHERE m.contract_signing_time >= '"+(tyear-1)+"' AND m.contract_signing_time <= '"+tyear+"' group by months";
}
// 统计今年12个月的项目数
tyearListData = cnitsecEManageDao.retrieveListBySql(tsql);// 查询本年度项目sql
// object[0]:公司名称
// object[1]:月份
// object[2]:月份对应的项目数
// 从数据库中读取数据,依次按月份写入数目,如果本月项目数没有,补0
List<Integer> tCount = new ArrayList<Integer>();// 今年的项目数列表
if (tyearListData != null) {
for (int i = 1; i <= 12; i++) {
boolean flag = false;
for (Object[] object : tyearListData) {
if (i == Integer.valueOf((String) object[1])) {
tCount.add(((BigInteger) object[2]).intValue());
flag = true;
break;
}
}
if (!flag) {
tCount.add(0);
}
}
}
// 统计去年12个月的项目数
lyearListData = cnitsecEManageDao.retrieveListBySql(lsql);// 查询去年度项目sql
// object[0]:公司名称
// object[1]:月份
// object[2]:月份对应的项目数
// 从数据库中读取数据,依次按月份写入数目,如果本月项目数没有,补0
List<Integer> lCount = new ArrayList<Integer>();// 去年的项目数列表
if (lyearListData != null) {
for (int i = 1; i <= 12; i++) {
boolean flag = false;
for (Object[] object : lyearListData) {
if (i == Integer.valueOf((String) object[1])) {
lCount.add(((BigInteger) object[2]).intValue());
flag = true;
break;
}
}
if (!flag) {
lCount.add(0);
}
}
}
//组织本年度的map数据
Map tyearMap = new HashMap();
tyearMap.put("name", years.get(0));
tyearMap.put("type", "line");
tyearMap.put("data", tCount);
projectNumByMonth.add(tyearMap);
//组织去年的map数据
Map lyearMap = new HashMap();
lyearMap.put("name", years.get(1));
lyearMap.put("type", "line");
lyearMap.put("data", lCount);
projectNumByMonth.add(lyearMap);
lineMap.put("legends", years);
lineMap.put("xAxis", months);
lineMap.put("series", projectNumByMonth);
return lineMap;
}
fastjson工具类:内部封装看不到,粘贴别人的
FastjsonPropertyFilter:
package com.echarts.utils.json;
import java.util.HashSet;
import java.util.Set;
import com.alibaba.fastjson.serializer.PropertyFilter;
/**
* FASTJSON属性过滤器
*
* @author
* @version 1.0
* @date 2015年3月12日
*/
public class FastjsonPropertyFilter implements PropertyFilter {
private final Set<String> includes = new HashSet<String>();
private final Set<String> excludes = new HashSet<String>();
public boolean apply(Object source, String name, Object value) {
if (excludes.contains(name)) {
return false;
}
if (excludes.contains(source.getClass().getSimpleName() + "." + name)) {
return false;
}
if (includes.size() == 0 || includes.contains(name)) {
return true;
}
if (includes.contains(source.getClass().getSimpleName() + "." + name)) {
return true;
}
return false;
}
public Set<String> getIncludes() {
return includes;
}
public Set<String> getExcludes() {
return excludes;
}
}
JsonUtils:
package com.echarts.utils.json;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* JSON工具类
*
* @author
* @version 1.0
* @date 2015年3月12日
*/
public class JsonUtils {
public static void writeJson(Object object,
HttpServletRequest request, HttpServletResponse response) {
writeJsonByFilter(object, null, null, request, response);
}
public static void writeJsonByIncludesProperties(Object object, String[] includesProperties,
HttpServletRequest request, HttpServletResponse response) {
writeJsonByFilter(object, includesProperties, null, request, response);
}
public static void writeJsonByExcludesProperties(Object object, String[] excludesProperties,
HttpServletRequest request, HttpServletResponse response) {
writeJsonByFilter(object, null, excludesProperties, request, response);
}
public static void writeJsonByFilter(Object object, String[] includesProperties,
String[] excludesProperties, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter writer = null;
try {
writer = response.getWriter();
FastjsonPropertyFilter filter = new FastjsonPropertyFilter();
if (includesProperties != null && includesProperties.length > 0) {
filter.getIncludes().addAll(Arrays.<String> asList(includesProperties));
}
if (excludesProperties != null && excludesProperties.length > 0) {
filter.getExcludes().addAll(Arrays.<String> asList(excludesProperties));
}
String userAgent = request.getHeader("User-Agent");
if (userAgent.indexOf("MSIE") > -1 && (userAgent.indexOf("MSIE 6") > -1)) {
writer.write(JSON.toJSONString(object, filter,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.BrowserCompatible));
} else {
writer.write(JSON.toJSONString(object, filter,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect));
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
}
结果展示: