使用环境:struts2 json
使用目的:统计图
流程:只需要在jsp页面配置,就能实现数据的线状图,柱状图,饼状图的统计
一个例子:
1.JSP页面:
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>浙江省食品药品监督管理局公众服务平台</title> <link href="/css/main.css" rel="stylesheet" type="text/css" /> <link href="/css/column.css" rel="stylesheet" type="text/css" /> <link href="/css/myChart.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="/js/jquery-1.5.2.min.js" ></script> <script language="javascript" type="text/javascript" src="/jqPlugIn/highcharts/highcharts.js"></script> <script language="javascript" type="text/javascript" src="/js/myChart.js" ></script> <script language="javascript" type="text/javascript" src="/js/myChartTheme.js" ></script> <script language="javascript" type="text/javascript" src="/My97DatePicker/WdatePicker.js"></script> <script type="text/javascript"> $(function(){ var sql = "select count(*) from tb_interac_consultative where time_treatment between ? and ? "; // 初始化线状图对象 var line = new MyChart(0); line.xAppend("已回复",sql+"and ct_treatment_status=?",new Array("1")); line.xAppend("回复中",sql+"and ct_treatment_status=?",new Array("2")); line.xAppend("未回复",sql+"and ct_treatment_status=?",new Array("0")); line.setTime("timeStart","timeEnd","timetype"); // 初始化柱状图对象 var column = new MyChart(1).cloneAttr(line); // 初始化饼状图对象 var pie = new MyChart(2); pie.fAppend("已回复",sql+"and ct_treatment_status=?",new Array("1")); pie.fAppend("回复中",sql+"and ct_treatment_status=?",new Array("2")); pie.fAppend("未回复",sql+"and ct_treatment_status=?",new Array("0")); pie.setTime("timeStart","timeEnd","timetype"); var myHighcharts = new MyHighcharts({ title:"科大公司在线咨询信息统计", subTitle:"Source:http://www.zjda.com", xTitle:"人数", yTitle:"信息条数", line:line, column:column, pie:pie }); myHighcharts.draw(0); }); </script> </head> <body> <jsp:include page="/header.jsp" flush="true"/> <div class="tenHeight"></div> <table width="960" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="706" align="left" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0" class="positionArea"> <tr> <td>当前位置:<a href="/">首页</a>>> <a href="/onlineInteract.jsp">互动信息</a>>> <a href="/zjfda/statistic/consultative.jsp">咨询信息统计</a></td> </tr> </table> <div class="tenHeight"></div> <!-- 数据统计图 --> <div id="myChart"> <!-- 导航 --> <ul id="navigation"> <li><a href="#" class="current">线状图</a></li> <li><a href="#">柱状图</a></li> <li><a href="#">饼状图</a></li> </ul> <!-- 统计图 --> <div id="container"></div> <!-- 如果没有用到时间动态统计则删除 --> <div id="timeselect"> 时间类型: <select id="timetype"> <!-- <option value="3">年份</option> --> <option value="2" selected="selected">月份</option> <!-- <option value="1">天数</option> --> </select> 时间段:<input type="text" class="Wdate" id="timeStart" size="12" onclick="WdatePicker()" value="2012-01-01"/> 至<input type="text" class="Wdate" id="timeEnd" size="12" onclick="WdatePicker()" value="2012-12-30"/> </div> </div> <!-- 数据统计图 --> <div class="tenHeight"></div> <jsp:include page="/footer.jsp" flush="true"/> </body> </html>2.myChart.js
// 封装请求参数对象 var Emtoy = function(f,name,sql,params){ this.f = -1; this.name = name; this.sql = sql; if(params!=null){ this.params = params.concat(); }else{ this.params = null } } /** * 统计图对象对应的JAVA类MyChart.java * @param : typechart * 0表示线状图对象 * 1表示柱状图对象 * 2表示单饼状图对象 * 3表示内嵌饼图对象 */ var MyChart = function(typechart){ this.title;//统计图标题 this.subtitle;//统计图副标题 this.xTitle;//x轴标题 this.yTitle;//主轴标题 this.typedb;//服务器端的数据源 this.typechart = typechart;//统计图类类型 this.typetime = 0;//统计的时间类型 this.emtoys = new Array();//需要统计的参数 this.smtoys = new Array();//需要统计的参数,当统计图是内嵌饼图的时候用到 this.categories = new Array();//发送到服务器时间分段 this.categoriesLocal = new Array();//本地轴分段名称 this.timeAry = new Array();//保存从页面取得的时间的ID /** * x轴统计内容 * @param : name 系列名称 * @param : sql 查询语句 * @param : params 查询参数 */ this.xAppend = function(name,sql,params){ this.emtoys.push(new Emtoy(null,name,sql,params)); } /** * y轴系列内容,时间段查询用 * @param : name 时间段名称 * @param : time 时间 */ this.yAppend = function(name,time){ this.categories.push(time); this.categoriesLocal.push(name); } /** * 饼状图外层 * @param : name 系列名称 * @param : sql 查询语句 * @param : params 查询参数 */ this.fAppend = function(name,sql,params){ this.emtoys.push(new Emtoy(null,name,sql,params)); } /** * 饼状图内层 * @param : f 外层饼状图的标志 * @param : name 系列名称 * @param : sql 查询语句 * @param : params 查询参数 */ this.sAppend = function(f,name,sql,params){ this.smtoys.push(new Emtoy(f,name,sql,params)); } /** * 保存y轴系列时间段,从页面读取 * @param : timeStart 页面开始时间的ID * @param : timeEnd 页面结束时间的ID * @param : timetype 页面时间的类型,年或月或日 */ this.setTime = function(timeStart,timeEnd,timetype){ this.timeAry.push(timeStart); this.timeAry.push(timeEnd); this.timeAry.push(timetype); } /** * 设置y轴系列时间段,从页面读取 * @param : timeStart 页面开始时间的ID * @param : timeEnd 页面结束时间的ID * @param : timetype 页面时间的类型,年或月或日 */ this.getPageTime = function(){ if(this.timeAry.length!=0){ this.categories = new Array(); this.categories.push($("#"+this.timeAry[0]).val()); this.categories.push($("#"+this.timeAry[1]).val()); this.typetime = $("#"+this.timeAry[2]).val(); this.xTitle = $("#"+this.timeAry[2]).find("option:selected").text(); }else{ this.categories = null; } } /** * 复制一个对象 * @param : chart 目标对象 * @param : typechart 指定类型 */ this.cloneAttr = function(chart){ this.title = chart.title; this.subtitle = chart.subtitle; this.xTitle = chart.xTitle; this.yTitle = chart.yTitle; this.typedb = chart.typedb; this.typetime = chart.typetime; this.emtoys = chart.emtoys; this.smtoys = chart.smtoys; this.categories = chart.categories; this.categoriesLocal = chart.categoriesLocal; this.timeAry = chart.timeAry; return this; } } // 统计图的触发绑定与整理 var MyHighcharts = function(options){ tempHighcharts = this; var defaults = { typedb:0, title:"这是默认标题", subTitle:"这是默认副标题", xTitle:"x轴说明", yTitle:"y轴说明", line:null, column:null, pie:null }; var options = $.extend(defaults, options); /** ajax请求,这里用POST提交,因为参数可能拼接的较长 */ this.draw = function(i){ // 显示等待信息 $("#container").empty(); $("#container").append("<p style=\"text-align: center\"><img src=\"/images/loading.gif\" alt=\"加载中,请稍候...\" /></p>"); this.initLocalData(i,options); $.post("/stat/chart!draw.do",this.initParams(tempChart),this.callBackChart); } /** 数据本地化请求*/ this.initLocalData = function(i,options){ switch (i) { case 0: tempChart = options.line; break; case 1: tempChart = options.column; break; default: tempChart = options.pie; break; } tempChart.title = options.title; tempChart.subtitle = options.subtitle; tempChart.xTitle = options.xTitle; tempChart.yTitle = options.yTitle; tempChart.typedb = options.typedb; } /** 参数处理 */ this.initParams = function(myChart){ var param = new Object(); var timeStr = "1950#1950"; if(myChart.time != 0){ myChart.getPageTime(); } param["myChart.typedb"] = myChart.typedb; param["myChart.typechart"] = myChart.typechart; param["myChart.typetime"] = myChart.typetime; if(myChart.categories!=undefined && myChart.categories!=null){ param["myChart.categoriesStr"] = this.getFztoStr(myChart.categories); }else{ timeStr = ""; } if(myChart.emtoys!=undefined && myChart.emtoys!=null){ for(var i=0; i<myChart.emtoys.length; i++){ param["myChart.emtoys["+i+"].name"] = myChart.emtoys[i].name; param["myChart.emtoys["+i+"].sql"] = myChart.emtoys[i].sql; if(myChart.emtoys[i].params!=null && myChart.emtoys[i].params!=""){ param["myChart.emtoys["+i+"].params"] = (timeStr==""?timeStr:timeStr+"#")+this.getFztoStr(myChart.emtoys[i].params); }else{ if(timeStr != ""){ param["myChart.emtoys["+i+"].params"] = timeStr; } } } for(var k=0; k<myChart.smtoys.length; k++){ param["myChart.smtoys["+k+"].f"] = myChart.smtoys[k].f; param["myChart.smtoys["+k+"].name"] = myChart.smtoys[k].name; param["myChart.smtoys["+k+"].sql"] = myChart.smtoys[k].sql; param["myChart.smtoys["+k+"].params"] = "2010#2050"+myChart.smtoys[k].params if(myChart.smtoys[k].params!=null && myChart.smtoys[k].params!=""){ param["myChart.smtoys["+k+"].params"] = timeStr==""?timeStr:(timeStr+"#")+this.getFztoStr(myChart.smtoys[k].params) }else{ if(timeStr != ""){ param["myChart.smtoys["+k+"].params"] = timeStr; } } } } return param; } this.getFztoStr = function(array){ var str = ""; for(var i=0; i<array.length; i++){ if(i == 0){ str = str+array[i]; }else{ str = str+"#"+array[i]; } } return str; } /** 返回数据处理 */ this.callBackChart = function(data){ if(tempChart.timetype != 0){ tempChart.categoriesLocal = data.myChart.categoriesLocal; } switch (data.myChart.typechart) { case 0://线状图 tempHighcharts.setClass(0); tempHighcharts.callBackLine(data); break; case 1://柱状图 tempHighcharts.setClass(1); tempHighcharts.callBackColumn(data); break; case 2://单饼图 tempHighcharts.setClass(2); tempHighcharts.callBackPie(data); break; default://内嵌饼图 tempHighcharts.setClass(2); tempHighcharts.callBackDonutPie(data); break; } } // line请求返回函数的处理 this.callBackLine = function(data){ new Highcharts.Chart({ chart: { renderTo: 'container', type: 'line' }, title: { text: tempHighcharts.getTimeTitle(tempChart.categoriesLocal) }, subtitle: { text: tempChart.subtitle }, xAxis: { title: { text: tempChart.xTitle, align: 'high' }, categories: tempChart.categoriesLocal }, yAxis: { title: { align: 'high', offset: 0, text: tempChart.yTitle, rotation: 0, y: -10 }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, plotOptions: { spline: { marker: { radius: 4, lineColor: '#666666', lineWidth: 1 } } }, legend:{ borderWidth:0 }, tooltip: { crosshairs: true, shared: true }, series: data.myChart.series }); } // column请求返回函数的处理 this.callBackColumn = function(data){ new Highcharts.Chart({ chart: { renderTo: 'container', type: 'column' }, title: { text: tempHighcharts.getTimeTitle(tempChart.categoriesLocal) }, subtitle: { text: tempChart.subtitle }, xAxis: { title: { text: tempChart.xTitle, align: 'high' }, categories: tempChart.categoriesLocal }, yAxis: { title: { align: 'high', offset: 0, text: tempChart.yTitle, rotation: 0, y: -10 }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, plotOptions: { spline: { marker: { radius: 4, lineColor: '#666666', lineWidth: 1 } } }, legend:{ borderWidth:0 }, tooltip: { formatter: function() { return ''+this.x+'<br/>'+ this.series.name +': '+ this.y; } }, series: data.myChart.series }); } // 单饼状图 this.callBackPie = function(data){ new Highcharts.Chart({ chart: { renderTo: 'container', plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type:'pie' }, title: { text: tempHighcharts.getTimeTitle(tempChart.categoriesLocal) }, subtitle: { text: tempChart.subtitle }, tooltip: { formatter: function() { return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 2) +' %'; } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorColor: '#000000', formatter: function() { return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 2) +' %'; } } } }, series: data.myChart.series_pie }); } // 内嵌饼状图 this.callBackDonutPie = function(data){ var dt = tempChart.comb(data); new Highcharts.Chart({ chart: { renderTo: 'container', type: 'pie' }, title: { text: tempHighcharts.getTimeTitle(data.myChart.categories) }, subtitle: { text: tempChart.subtitle }, yAxis: { title: { text: 'Total percent market share' } }, plotOptions: { pie: { shadow: false } }, tooltip: { formatter: function() { return '<b>'+ this.point.name +'</b>: '+ this.y +' %'; } }, series: dt }); } // 对内嵌饼状图异步请求产生的数据进行整理然后展示到JSP页面上 this.comb = function(data){ var colors = Highcharts.getOptions().colors; var pie1 = data.myChart.series_pie[0]; var pie2 = data.myChart.series_pie[1]; var firstData = []; var secondData = []; for (var i = 0; i < pie1.data.length; i++) { firstData.push({ name: pie1.data[i][0], y: pie1.data[i][1], color: colors[i] }); } for (var i = 0; i < pie2.data.length; i++) { secondData.push({ name: pie2.data[i][0], y: pie2.data[i][1], color:this.getColor(colors,pie2,pie2.data[i]) }); } var dt = []; dt.push({ name: 'first', data: firstData, size: '60%', dataLabels: { formatter: function() { return this.y > -1 ? this.point.name : null; }, color: 'white', distance: -30 } }); dt.push({ name: 'second', data: secondData, innerSize: '60%', dataLabels: { formatter: function() { return this.y > -1 ? '<b>'+ this.point.name +':</b> '+ this.y +'%' : null; } } }); return dt; } // 内嵌饼状图-子类的颜色 this.getColor = function(colors,pie2,dt){ var one = 0; var all = 0; var tempAy = []; for (var i = 0; i < pie2.data.length; i++) { if(pie2.data[i][2] == dt[2]){ tempAy.push(pie2.data[i][0]); } } all =tempAy.length; for (var i = 0; i < all; i++) { if(tempAy[i]== dt[0]){ one = i; continue; } } //alert(dt[0]+":"+one+"/"+all+":"+dt[2]); var brightness = 0.2 - (one / all) / 5 ; return Highcharts.Color(colors[dt[2]]).brighten(brightness).get(); } this.setClass = function(i){ var obj = $("#navigation a"); obj.attr("class",""); obj.eq(i).attr("class","current"); } this.getTimeTitle = function(categories){ if(categories == null){ return tempChart.title; } var lgh = categories.length; return this.pmt(categories[0],0)+"~"+this.pmt(categories[lgh-1],1)+tempChart.title; } this.pmt = function(str,i){//时间格式化 if(str.indexOf("#") != -1){ str = str.split("#")[i]; } if(str.length==10){ str = str.substring(0,4)+"年"+str.substring(5,7)+"月"+str.substring(8)+"号"; }else if(str.length==7){ str = str.substring(0,4)+"年"+str.substring(5)+"月"; }else{ str = str + "年"; } return str; } } $(function(){ $("#navigation a").click(function(){ var i = $("#navigation a").index($(this)); tempHighcharts.draw(i); }); });3.myChartTheme.js可以在官网下载,这里我作了少量改动,统计饼图的颜色作了调整
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1, spacingBottom:25 }, title: { style: { color: '#000', font: 'bold 14px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
<!-- 统计图ajax --> <package name="fda.bak" namespace="/stat" extends="common-ajax"> <action name="chart" class="com.zjfda.action.MyChartAction"> <result type="json"> chart\.categoriesLocal\[\d+\], chart\.series\[\d+\]\.name, chart\.series\[\d+\]\.data\[\d+\] chart\.series_pie\[\d+\]\.name, chart\.series_pie\[\d+\]\.data\[\d+\]\[\d+\] </result> </action> </package>
package com.zjfda.action; import javax.annotation.Resource; import com.common.ssh.action.BaseAction; import com.zjfda.bean.MyChart; import com.zjfda.service.MyChartService; /** * 线状、柱状、饼状(单饼与内嵌饼)统计图 * @author LQ. * */ @SuppressWarnings("serial") public class MyChartAction extends BaseAction{ public String draw(){ myChart = myChartService.drawMyChart(myChart); return SUCCESS; } @Resource MyChartService myChartService; private MyChart myChart; public MyChart getMyChart() { return myChart; } public void setMyChart(MyChart myChart) { this.myChart = myChart; } }
package com.zjfda.service; import java.util.ArrayList; import java.util.List; import com.common.ssh.dao.BaseJDBCDao; import com.common.ssh.service.BaseService; import com.common.util.Tools; import com.zjfda.bean.Emtoy; import com.zjfda.bean.MyChart; import com.zjfda.bean.Serie; import com.zjfda.bean.Serie_pie; public class MyChartService extends BaseService { public MyChart drawMyChart(MyChart myChart) { BaseJDBCDao dao; /* TODO 如果是多数据源,在这里通过myChart.getTypedb()判断选择哪个数据源*/ switch (myChart.getTypedb()) { case 1: dao = spDao; break; default: dao = fdaDao; break; } switch (myChart.getTypechart()) { case 3: myChart = getPieInline(dao,myChart); break; case 2: myChart = getPie(dao,myChart); break; case 1: myChart = getColumn(dao,myChart); break; default: myChart = getLine(dao,myChart); break; } return myChart; } // 内嵌饼图 private MyChart getPieInline(BaseJDBCDao dao, MyChart myChart) { List<Serie_pie> series_pie = new ArrayList<Serie_pie>(); String[] categories = getCombCate(myChart); myChart.setCategoriesLocal(categories); series_pie.add(getPieSeries(dao,myChart.getEmtoys(),categories)); series_pie.add(getPieSeries(dao,myChart.getSmtoys(),categories)); myChart.setSeries_pie(series_pie); return myChart; } // 单饼图 private MyChart getPie(BaseJDBCDao dao, MyChart myChart) { List<Serie_pie> series_pie = new ArrayList<Serie_pie>(); String[] categories = getCombCate(myChart); myChart.setCategoriesLocal(categories); series_pie.add(getPieSeries(dao,myChart.getEmtoys(),categories)); myChart.setSeries_pie(series_pie); return myChart; } // 柱状图 private MyChart getColumn(BaseJDBCDao dao, MyChart myChart) { return getLine(dao,myChart); } // 线状图 private MyChart getLine(BaseJDBCDao dao, MyChart myChart) { List<Emtoy> emtoys = myChart.getEmtoys(); String[] categories = getCombCate(myChart); myChart.setCategoriesLocal(categories); List<Serie> series = new ArrayList<Serie>(); int length = categories.length; int line[]; Serie serie; for (Emtoy emtoy : emtoys) { line = new int[length]; for (int i = 0; i < length; i++) { line[i] = dao.count(emtoy.getSql(), getRealParams(emtoy.getParams().split("#"),categories,i)); } serie = new Serie(); serie.setName(emtoy.getName()); serie.setData(line); series.add(serie); } myChart.setSeries(series); return myChart; } // 饼图的数据处理 private Serie_pie getPieSeries(BaseJDBCDao dao, List<Emtoy> emtoys,String[] categories) { int length = emtoys.size(); Object pie[][] = new Object[length][3]; Emtoy emtoy; double temp; for (int i = 0; i < length; i++) { emtoy = emtoys.get(i); temp = dao.count(emtoy.getSql(),getRealParamsPie(emtoy.getParams(),categories)); pie[i][0] = emtoy.getName(); pie[i][1] = temp; pie[i][2] = emtoy.getF(); } Serie_pie serie_pie = new Serie_pie(); serie_pie.setData(pie); return serie_pie; } private Object[] getRealParamsPie(String paramsStr, String[] categories) { String[] params; if(paramsStr==null && categories==null){ params = new String[]{}; }else if(paramsStr!=null&&categories==null){ params = paramsStr.split("#"); }else if(paramsStr==null&&categories!=null){ params = new String[2]; int i = categories.length; params = combTimeStart(params,categories[0]); params = combTimeEnd(params,categories[i-1]); }else{ params = paramsStr.split("#"); int i = categories.length; params = combTimeStart(params,categories[0]); params = combTimeEnd(params,categories[i-1]); } return params; } private String[] combTimeEnd(String[] params, String timeStr) { int i = timeStr.indexOf("#"); if(i == -1){ params[1] = Tools.getTimeEnd(timeStr); }else{ params[1] = Tools.getTimeEnd(timeStr.substring(i+1)); } return params; } private String[] combTimeStart(String[] params, String timeStr) { int i = timeStr.indexOf("#"); if(i == -1){ params[0] = Tools.getTimeStart(timeStr); }else{ params[0] = Tools.getTimeStart(timeStr.substring(0,i)); } return params; } // 取得查询参数 private Object[] getRealParams(Object[] params, String[] categories,int w) { if(categories == null){ return params; } String timeStr; if(categories.length == 1){ timeStr = categories[0]; }else{ timeStr = categories[w]; } int i = timeStr.indexOf("#"); if(i == -1){ params[0] = Tools.getTimeStart(timeStr); params[1] = Tools.getTimeEnd(timeStr); }else{ params[0] = Tools.getTimeStart(timeStr.substring(0,i)); params[1] = Tools.getTimeEnd(timeStr.substring(i+1)); } return params; } // 取得时间段 private String[] getCombCate(MyChart myChart) { String[] newCates; String[] cates = myChart.getCategories(); switch (myChart.getTypetime()) { case 3: newCates = Tools.getYearList(cates[0], cates[1]); break; case 2: newCates = Tools.getMonthList(cates[0], cates[1]); break; case 1: newCates = Tools.getDayList(cates[0], cates[1]); break; default: newCates = cates; break; } return newCates; } }
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
应回复要求,贴出以下代码:
1.Tools.java
package com.common.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 常用工具 * * <p>字段串的操作,时间操作,MD5加密,上传文件 */ public class Tools { /** * md5加密 * @param x * @return 加密后的字符串 */ public static String md5(String x) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(x.getBytes("UTF8")); byte s[] = m.digest(); String result = ""; for (int i = 0; i < s.length; i++) { result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00) .substring(6); } return result; } catch (Exception e) { System.out.println("Tools.md5 加密[" + x + "]失败"); return null; } } /** * 格式化时间 * @param dateTime 要格式化的时间 * @param pattern 格式化的样式 * @return 已格式化的时间 */ public static String formatDateTime(Date dateTime, String pattern){ SimpleDateFormat dateFmt = new SimpleDateFormat(pattern); return dateTime==null?"":dateFmt.format(dateTime); } /** * 取得时间 * @param dateTime * @return 返回"2007"数据格式的字符串 */ public static String miniTime(Date dateTime) { return formatDateTime(dateTime,"yyyy"); } /** * 取得时间 * @param dateTime * @return 返回"2007-09-10"数据格式的字符串 */ public static String shortTime(Date dateTime) { return formatDateTime(dateTime,"yyyy-MM-dd"); } /** * 取得时间 * @param dateTime * @return 返回"2007-09-10 16:09"数据格式的字符串 */ public static String middleTime(Date dateTime) { return formatDateTime(dateTime,"yyyy-MM-dd HH:mm"); } /** * 取得时间 * @param dateTime * @return 返回"2007-09-10 16:09:00"数据格式的字符串 */ public static String longTime(Date dateTime) { return formatDateTime(dateTime,"yyyy-MM-dd HH:mm:ss"); } /** * 取得时间 * @param dateTime * @return 返回"20070910160900"数据格式的字符串 */ public static String minLongTime(Date dateTime) { return formatDateTime(dateTime,"yyyyMMddHHmmss"); } /** * 取得时间 * @param dateTime * @return 返回"2007年09月10号 16点09分00秒"数据格式的字符串 */ public static String longZhTime(Date dateTime) { return formatDateTime(dateTime,"yyyy年MM月dd号 HH点mm分ss秒"); } /** * 取得时间 * @param dateTime * @return 返回"2007/09/10 16:09:00.000"数据格式的字符串 */ public static String bigLongTime(Date dateTime) { return formatDateTime(dateTime,"yyyy/MM/dd HH:mm:ss.SSS"); } /** * 时间+-天数 :要得到的时间 * @param d 时间 * @param offset 天数 * @param bool true天数加false天数减 * @return */ public static Date changeDay(Date d,int offset,boolean bool){ Calendar calendar = Calendar.getInstance(); calendar.setTime(d); if(bool){ calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) + offset)); }else{ calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) - offset)); } return calendar.getTime(); } /** * 时间+-天数 :要得到的时间 * @param d 时间 * @param offset 天数 * @param bool true天数加false天数减 * @return */ public static Timestamp changeDay(Timestamp d,int offset,boolean bool){ Calendar calendar = Calendar.getInstance(); calendar.setTime(d); if(bool){ calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) + offset)); }else{ calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) - offset)); } return new Timestamp(calendar.getTimeInMillis()); } /** * 时间+-多少年 :要得到的时间 * @param d 时间 * @param offset 年数 * @param bool true年数加false年数减 * @return */ public static Date changeYear(Date d,int offset,boolean bool){ Calendar calendar = Calendar.getInstance(); calendar.setTime(d); if(bool){ calendar.set(Calendar.YEAR,(calendar.get(Calendar.YEAR) + offset)); }else{ calendar.set(Calendar.YEAR,(calendar.get(Calendar.YEAR) - offset)); } return calendar.getTime(); } /** * 时间+-多少年 :要得到的时间 * @param d 时间 * @param offset 年数 * @param bool true年数加false年数减 * @return */ public static Timestamp changeYear(Timestamp d,int offset,boolean bool){ Calendar calendar = Calendar.getInstance(); calendar.setTime(d); if(bool){ calendar.set(Calendar.YEAR,(calendar.get(Calendar.YEAR) + offset)); }else{ calendar.set(Calendar.YEAR,(calendar.get(Calendar.YEAR) - offset)); } return new Timestamp(calendar.getTimeInMillis()); } /** * 字符串是否可以转化成Double形式 * @param str * @return */ public static boolean isDouble(String str){ Pattern pattern = Pattern.compile("^[-\\+]?\\d+(\\.\\d*)?|\\.\\d+$"); return pattern.matcher(str).matches(); } /** * 是否可以转化为整数 * @param str * @return */ public static boolean isInteger(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } /** * 是否可以转化为整数加字符串 * @param str * @return */ public static boolean isStr(String str){ Pattern pattern = Pattern.compile("[a-zA-Z0-9]*"); return pattern.matcher(str).matches(); } /** * 是否可以转化为数字 * @param str * @return */ public static boolean isNumber(String str){ return isInteger(str) || isDouble(str); } /** * 取得结束的时间 * 如果参数为2007,则返回2007-12-31 23:59:59 * 如果参数为2007-08 ,则返回2007-08-31 23:59:59 * 如果参数为2007-09 ,则返回2007-09-30 23:59:59 * 如果参数为2007-09-09 ,则返回2007-09-09 23:59:59 * @param time yyyy yyyy-MM yyyy-MM-dd形式 * @return yyyy-MM-dd HH:mm:ss */ public static String getTimeEnd(final String time){ Calendar timeEnd = Calendar.getInstance(); if(time!=null){ if(time.length()==4){ timeEnd.set(Calendar.YEAR, Integer.parseInt(time)); timeEnd.set(Calendar.MONTH,11); timeEnd.set(Calendar.DATE, 1); timeEnd.roll(Calendar.DATE, -1); timeEnd.set(Calendar.HOUR_OF_DAY, 23); timeEnd.set(Calendar.MINUTE, 59); timeEnd.set(Calendar.SECOND, 59); } if(time.length()==7){ timeEnd.set(Calendar.YEAR, Integer.parseInt((time.split("-"))[0])); timeEnd.set(Calendar.MONTH,Integer.parseInt((time.split("-"))[1])-1); timeEnd.set(Calendar.DATE, 1); timeEnd.roll(Calendar.DATE, -1); timeEnd.set(Calendar.HOUR_OF_DAY, 23); timeEnd.set(Calendar.MINUTE, 59); timeEnd.set(Calendar.SECOND, 59); } if(time.length()==10){ timeEnd.set(Calendar.YEAR, Integer.parseInt((time.split("-"))[0])); timeEnd.set(Calendar.MONTH,Integer.parseInt((time.split("-"))[1])-1); timeEnd.set(Calendar.DATE, Integer.parseInt((time.split("-"))[2])); timeEnd.set(Calendar.HOUR_OF_DAY, 23); timeEnd.set(Calendar.MINUTE, 59); timeEnd.set(Calendar.SECOND, 59); } } return formatDateTime(timeEnd.getTime(),"yyyy-MM-dd HH:mm:ss"); } /** * 取得起始的时间 * 如果参数为2007,则返回2007-01-01 00:00:00 * 如果参数为2007-09 ,则返回2007-09-01 00:00:00 * 如果参数为2007-09-09 ,则返回2007-09-09 00:00:00 * @param time yyyy yyyy-MM yyyy-MM-dd形式 * @return yyyy-MM-dd HH:mm:ss */ public static String getTimeStart(final String time){ Calendar timeStart = Calendar.getInstance(); if(time!=null){ if(time.length()==4){ timeStart.set(Calendar.YEAR, Integer.parseInt(time)); timeStart.set(Calendar.MONTH,0); timeStart.set(Calendar.DATE, 1); timeStart.set(Calendar.HOUR_OF_DAY, 0); timeStart.set(Calendar.MINUTE, 0); timeStart.set(Calendar.SECOND, 0); } if(time.length()==7){ timeStart.set(Calendar.YEAR, Integer.parseInt((time.split("-"))[0])); timeStart.set(Calendar.MONTH,Integer.parseInt((time.split("-"))[1])-1); timeStart.set(Calendar.DATE, 1); timeStart.set(Calendar.HOUR_OF_DAY, 0); timeStart.set(Calendar.MINUTE, 0); timeStart.set(Calendar.SECOND, 0); } if(time.length()==10){ timeStart.set(Calendar.YEAR, Integer.parseInt((time.split("-"))[0])); timeStart.set(Calendar.MONTH,Integer.parseInt((time.split("-"))[1])-1); timeStart.set(Calendar.DATE, Integer.parseInt((time.split("-"))[2])); timeStart.set(Calendar.HOUR_OF_DAY, 0); timeStart.set(Calendar.MINUTE, 0); timeStart.set(Calendar.SECOND, 0); } } return formatDateTime(timeStart.getTime(),"yyyy-MM-dd HH:mm:ss"); } /** * 判断str是否为空或为all,成立返回false,反之返回true * @param str * @return */ public static boolean isActive(String str){ return str!=null && !str.trim().equals("all") && !str.trim().equals(""); } /** * 判断str是否为空或为空字符串,成立返回false,反之返回true * @param str * @return */ public static boolean isNullChar(String str){ return str!=null && !str.trim().equals(""); } /** * yyyy-MM-dd hh:mm:ss转换为date类型 * @param str */ public static Date getDate(String str) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = null; try { date = df.parse(str); } catch (Exception e) { System.out.println("Tools.getDate失败"); } return date; } /** * 数据处理,保留precision位小数 * @param val 要处理的数字 * @param precision 要保留的小数位数 * @return */ public static Double roundDouble(double val, int precision) { Double ret = null; try { double factor = Math.pow(10, precision); ret = Math.floor(val * factor + 0.5) / factor; } catch (Exception e) { e.printStackTrace(); } return ret; } /** * 获得随机数字符串 * * @param length * 需要获得随机数的长度 * @param type * 随机数的类型:'0':表示仅获得数字随机数;'1':表示仅获得字符随机数;'2':表示获得数字字符混合随机数 * @return */ public static String getRandomStr(int length, int type) { String strRandom = ""; Random rnd = new Random(); if (length < 0) length = 5; if ((type > 2) || (type < 0)) type = 2; switch (type) { case 0: for (int iLoop = 0; iLoop < length; iLoop++) { strRandom += Integer.toString(rnd.nextInt(10)); } break; case 1: for (int iLoop = 0; iLoop < length; iLoop++) { strRandom += Integer.toString((35 - rnd.nextInt(10)), 36); } break; case 2: for (int iLoop = 0; iLoop < length; iLoop++) { strRandom += Integer.toString(rnd.nextInt(36), 36); } break; } return strRandom; } public static boolean chkInputByRegex(String inputString,String regexString){ Pattern p=Pattern.compile(regexString); Matcher m=p.matcher(inputString); return m.matches(); } /** * 取得时间段内的年的日期集合 * @param beginDateStr * @param endDateStr * @return */ public static String[] getYearList(String dateFrom, String dateEnd) { dateFrom = dateFrom.substring(0,4); dateEnd = dateEnd.substring(0,4); int df = Integer.valueOf(dateFrom); int de = Integer.valueOf(dateEnd); List<String> dateList = new ArrayList<String>(); for (int i = df; i <= de; i++) { dateList.add(""+i); } String[] dateArray = new String[dateList.size()]; dateList.toArray(dateArray); return dateArray; } /** * 取得时间段内的月的日期集合 * @param beginDateStr * @param endDateStr * @return */ public static String[] getMonthList(String dateFrom, String dateEnd) { //指定要解析的时间格式 SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); List<String> dateList = new ArrayList<String>(); //定义一些变量 Date beginDate = null; Date endDate = null; GregorianCalendar beginGC = null; GregorianCalendar endGC = null; try { //将字符串parse成日期 beginDate = f.parse(dateFrom); endDate = f.parse(dateEnd); //设置日历 beginGC = new GregorianCalendar(); beginGC.setTime(beginDate); endGC = new GregorianCalendar(); endGC.setTime(endDate); //直到两个时间相同 while(beginGC.getTime().compareTo(endGC.getTime())<=0){ dateList.add(beginGC.get(Calendar.YEAR) + "-" + getM(beginGC.get(Calendar.MONTH)+1)); //以月为单位,增加时间 beginGC.add(Calendar.MONTH,1); } dateList.add(beginGC.get(Calendar.YEAR) + "-" + getM(beginGC.get(Calendar.MONTH)+1)); String[] dateArray = new String[dateList.size()]; dateList.toArray(dateArray); return dateArray; } catch(Exception e) { e.printStackTrace(); return null; } } private static String getM(int i) { String st = ""+i; st = "00".substring(st.length())+st; return st; } /** * 取得时间段内的日的日期集合 * @param dateFrom * @param dateEnd * @return */ public static String[] getDayList(String dateFrom, String dateEnd){ long time = 1l; long perDayMilSec = 24 * 60 * 60 * 1000; List<String> dateList = new ArrayList<String>(); dateList.add(dateFrom); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); while (true) { try { time = sdf.parse(dateFrom).getTime(); time = time + perDayMilSec; dateFrom = sdf.format(new Date(time)); if (dateFrom.compareTo(dateEnd) < 0) { dateList.add(dateFrom); } else { break; } } catch (Exception e) { e.printStackTrace(); break; } } dateList.add(dateEnd); String[] dateArray = new String[dateList.size()]; dateList.toArray(dateArray); return dateArray; } /** * 取得map中的真实值 * @param map * @param key * @return */ public static String getValue(Map<String, Object> map, String key) { Object obj = map.get(key); if(obj == null) return null; else if(!obj.getClass().isArray()) return obj.toString(); else return Arrays.toString((Object[])obj).replace("[", "").replace("]", ""); } public static void main(String args[]){ } }2.MyChart.java
package com.zjfda.bean; import java.util.List; import java.util.Map; /** * 数据统计图参数与结果的传递封装 * @author LQ */ public class MyChart { /* * 指定数据源 * 适用于数据统计来自多个数据源时 */ private int typedb; /* * 统计类型 * 0线状图,1柱状图,2单饼图,3内嵌饼图 */ private int typechart; /* * 统计时间类型 * 0自定义,1天,2月,3年 */ private int typetime; // 封装Line,column传递到jsp页面的数据 public List<Serie> series; public List<Serie_pie> series_pie; /* * 封装统计查询参数 */ private List<Emtoy> emtoys; private List<Emtoy> smtoys;//如果是内嵌饼图,这个参数封装的是内嵌饼图的参数数据 /* * 封装y轴类型时间类型 */ private String[] categories;//时间参数 private String[] categoriesLocal;//时间参数 private String categoriesStr; /* * 封装自定义的参数 */ private Map<String,Object> map; public int getTypedb() { return typedb; } public void setTypedb(int typedb) { this.typedb = typedb; } public int getTypechart() { return typechart; } public void setTypechart(int typechart) { this.typechart = typechart; } public int getTypetime() { return typetime; } public void setTypetime(int typetime) { this.typetime = typetime; } public List<Serie> getSeries() { return series; } public void setSeries(List<Serie> series) { this.series = series; } public List<Serie_pie> getSeries_pie() { return series_pie; } public void setSeries_pie(List<Serie_pie> series_pie) { this.series_pie = series_pie; } public List<Emtoy> getEmtoys() { return emtoys; } public void setEmtoys(List<Emtoy> emtoys) { this.emtoys = emtoys; } public List<Emtoy> getSmtoys() { return smtoys; } public void setSmtoys(List<Emtoy> smtoys) { this.smtoys = smtoys; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public String[] getCategories() { if(categoriesStr==null || categoriesStr.equals("")){ return null; } if(categoriesStr.indexOf("#")!=-1){ return categoriesStr.split("#"); }else{ return new String[]{categoriesStr}; } } public void setCategories(String[] categories) { this.categories = categories; } public String[] getCategoriesLocal() { return categoriesLocal; } public void setCategoriesLocal(String[] categoriesLocal) { this.categoriesLocal = categoriesLocal; } public String getCategoriesStr() { return categoriesStr; } public void setCategoriesStr(String categoriesStr) { this.categoriesStr = categoriesStr; } }
3.Emtoy.java
package com.zjfda.bean; /** * 封装统计参数 * @author LQ * */ public class Emtoy{ // 标志 public int f; // 系列名称 public String name; // 查询语句 public String sql; // 查询参数 public String params; public int getF() { return f; } public void setF(int f) { this.f = f; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public Emtoy() { super(); } }4.Serie.java
package com.zjfda.bean; /** * 封装展示的统计数据 * @author LQ * */ public class Serie { // 系列名称 public String name; // 封装线状图或柱状图数据 public int data[]; public String getName() { return name; } public void setName(String name) { this.name = name; } public int[] getData() { return data; } public void setData(int[] data) { this.data = data; } }
package com.zjfda.bean; /** * 封装展示的统计数据 * @author LQ * */ public class Serie_pie { // 系列名称 public String name; // 封装饼状图数据 public Object data[][]; public String getName() { return name; } public void setName(String name) { this.name = name; } public Object[][] getData() { return data; } public void setData(Object[][] data) { this.data = data; } }