jFreeChart连接oracle数据库数据实现顺序图,饼形图和柱状图

首先:准备jFreeChart.jar包,并加到/WEB-INF/lib目录下。
其次:在web.xml配置文件中加入下列东东:
<!-- 配置jFreeChart -->
<servlet>
        <servlet-name>DisplayChart</servlet-name>
        <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
    </servlet>
<servlet-mapping>
        <servlet-name>DisplayChart</servlet-name>
        <url-pattern>/servlet/DisplayChart</url-pattern>
    </servlet-mapping>
第三:建立数据表:
总结报告(zjbg)
表结构描述
描述 名称 类型           可空          备注(P为主键)
报告编号 zjbgid Number(10)      Not null           P
执行时间 Zxsj Date        Not null
发送数量 fssl Number(10) Null
失效数量 sxsl Number(10) Null
备注 bz Varchar2(1000) Null
第四:现在的要求是要查询出从执行起始时间到中终止时间段内每日的失效率;
先写一个查询界面select.jsp如下:
<%@ page contentType="text/html;charset=GBK"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<html>
<script language="javascript" src="js/PopupCalendar.js"></script>
<script>
var oCalendarChs=new PopupCalendar("oCalendarChs"); //初始化控件时,请给出实例名称:oCalendarChs
oCalendarChs.weekDaySting=new Array("日","一","二","三","四","五","六");
oCalendarChs.monthSting=new Array("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");
oCalendarChs.oBtnTodayTitle="今天";
oCalendarChs.oBtnCancelTitle="取消";
oCalendarChs.Init();
</script>
<script type="text/javascript">
  function click_Submit(){
var tem1 = document.zjbgForm.startTime.value;
var tem2 = document.zjbgForm.endTime.value;
    if(tem1==""){
      alert("请输入起始时间");
      return ;
    }if(tem2==""){
      alert("请输入终止时间");
      return ;
    }
    if(compareDate(tem1,tem2)==1){ 
            alert(tem1+"-"+tem2+":起始时间要小于等于终止时间");
    return false;  
    }else{
       document.zjbgForm.submit();
   return true;
}
}
function compareDate(beginip1,endip){
var beginip=beginip1;
if(beginip!="" && endip!=""){
var bgn=beginip;
var end=endip;
if(bgn==end)
return 0;
var tmpnum1="";
var tmpnum2="";
//判断起始date1小于等于终止date2
for(var i=0;i<4;i++){
var index1=bgn.indexOf("-");
var index2=end.indexOf("-");
    var  tmp1;
var  tmp2;
if(-1!=index1){
tmp1 = bgn.substring(0,index1);
tmp2 = end.substring(0,index2);
bgn=bgn.substring(index1+1,bgn.length);
end=end.substring(index2+1,end.length);
}else{
tmp1=bgn.substring(0,bgn.length);
tmp2=end.substring(0,end.length);
        }
tmpnum1=tmpnum1+tmp1;
tmpnum2=tmpnum2+tmp2;
}
if(1==compInteger(tmpnum1,tmpnum2)){
return 1;
}
   }
    if(beginip!="" && endip==""){
   return 1;
  }
   if(beginip=="" && endip!=""){
   return 1;
   }
return 0;
}  
function  compInteger(strValue1, strValue2){
    var  nValue1, nValue2 ;
      //判断第一个参数的有效性
      if (fucCheckNUM(strValue1) == 0)
        return -1 ;
//判断第二个参数的有效性
      if (fucCheckNUM(strValue2) == 0)
            return -2 ;
      //转换后比较
      nValue1 = parseInt(strValue1) ;
      nValue2 = parseInt(strValue2) ;
      if (nValue1 == nValue2){
        return 0 ;
        }
        if (nValue1 < nValue2){
         return 2 ;
        }
        if (nValue1 > nValue2){
        return 1 ;
        }
}
function fucCheckNUM(NUM){
    var i,j,strTemp;
    strTemp="0123456789.";
    if ( NUM.length == 0) return 0;
    for (i=0;i<NUM.length;i++){
    j = strTemp.indexOf(NUM.charAt(i));
    if (j==-1){
    return 0;
    }
    }
    return 1;
}
  </script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>时间查询页面</title>
</head>
<body>
<html:form action="/zjbgTimeSeriesChart.do" method="post">
<table width="100%" border="0" align="center" bgcolor="98B6E8"
style='font-size: 12px'>
<tr>
<td height="25" colspan="3" background="images/btbjs.gif">
<div align="center" class="t0bt">
<strong>总结报告</strong>
</div>
</td>
</tr>
<tr bgcolor="#EFF6FE" class="t01">
<td>
执行时间范围:
</td>
<td bgcolor="#FFFFFF">
<html:text property="startTime" readonly="true"
onclick='getDateString(this,oCalendarChs)' />
-
<html:text property="endTime" readonly="true"
onclick='getDateString(this,oCalendarChs)' />
</td>
<td bgcolor="#FFFFFF">
<img src="images/search.gif" style="cursor: hand;" border="0"
onclick="click_Submit()">
<IMG src="images/reset.gif" style="cursor: hand;" border="0"
onClick="zjbgForm.reset()">
</td>
</tr>
</table>
</html:form>
</body>
</html>
第五:在struts-config.xml配置文件中加入:
<!-- 配置总结报告zjbgForm-->
<form-bean name="zjbgForm"
         type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="zjbgId" type="java.lang.Integer" />
<form-property name="startTime" type="java.lang.String" />
<form-property name="endTime" type="java.lang.String" />
         <form-property name="fssl" type="java.lang.Integer" />
         <form-property name="sxsl" type="java.lang.Integer" />
         <form-property name="bz" type="java.lang.String" />
</form-bean>

<action path="/zjbgTimeSeriesChart"
             type="com.wanglihu.action.ZjbgTimeSeriesChartAction"
             name="zjbgForm"
             scope="request">   
         <forward name="chartForward"   path="/report/chart.jsp"/>         
     </action>
第六:建立com.wanglihu.action.ZjbgTimeSeriesChartAction.java类
public class ZjbgTimeSeriesChartAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String status="chartForward";
String  startTime=request.getParameter("startTime");
String  endTime=request.getParameter("endTime");
ZjbgDAO  zjbgDao=new ZjbgDAO();
int sjjgs=zjbgDao.getTimesjByStartOrEndTime(startTime, endTime);
List<Zjbg> list=new ArrayList<Zjbg>();
if(sjjgs<0&&sjjgs>31){
System.out.println("您只能查询间隔一个月的失效数据!");
}
//时间向后退
for(int i=0;i<=sjjgs;i++){
//从起始执行时间每增加一天得到的时间-SQL
String sql="select to_date('"+startTime+"','yyyy-mm-dd')+"+i+" as zxsj from dual";
//从起始执行时间每增加一天得到的时间
String zxsj=zjbgDao.getZxsjBySql(sql);
//查询某一天具体时间内总失效数量和发送数量,以及失效率
Zjbg zjbg=zjbgDao.getZjbgByTime(zxsj);
list.add(zjbg);
}
request.setAttribute("ZJBGLIST", list);
request.setAttribute("STARTTIME", startTime);
request.setAttribute("ENDTIME", endTime);
return mapping.findForward(status);
}
}
第七:新建Zjbg.java
public class Zjbg {
private double sxl;
private int sxsl;
private int fssl;
private String zxsj;
public double getSxl() {
return sxl;
}
public void setSxl(double sxl) {
this.sxl = sxl;
}
public int getSxsl() {
return sxsl;
}
public void setSxsl(int sxsl) {
this.sxsl = sxsl;
}
public int getFssl() {
return fssl;
}
public void setFssl(int fssl) {
this.fssl = fssl;
}
public String getZxsj() {
return zxsj;
}
public void setZxsj(String zxsj) {
this.zxsj = zxsj;
}
}
第八:新建ZjbgDAO.java
/**
* 查询两个日期之差多少个整数天
*/
public int getTimesjByStartOrEndTime(String startTime, String endTime) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int sjjgs = 0;
String sql = "select trunc(to_date('" + endTime
+ "','yyyy-mm-dd hh24:mi:ss'))-trunc(to_date('" + startTime
+ "','yyyy-mm-dd hh24:mi:ss')) as sjjgs from dual";
try {
con = DBconn.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
sjjgs = rs.getInt("sjjgs");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
}
}
return sjjgs;
}

/**
* 根据sql语句的参数查询某一时间第二天为哪一天并转换为String类型返回
*/
public String getZxsjBySql(String sql) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String zxsj = null;
try {
con = DBconn.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
zxsj = rs.getDate("zxsj").toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
}
}
return zxsj;
}

/**
* 查询某一天具体时间内总失效数量和发送数量,以及失效率
*/
public Rwbg getZjbgByTime(String zxsj) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Zjbg zjbg= new Zjbg();
String sql = "select sum(sxsl) as sxsl ,sum(fssl) as fssl from zjbg where to_char(zxsj,'yyyy-mm-dd')='"
+ zxsj + "'";
try {
con = DataBase.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
zjbg.setZxsj(zxsj);
zjbg.setSxsl(rs.getInt("sxsl"));
zjbg.setFssl(rs.getInt("fssl"));
if (rs.getInt("fssl") != 0) {
          zjbg.setSxl((double) rs.getInt("sxsl")/ rs.getInt("fssl"));
}
} else {
zjbg.setZxsj(zxsj);
zjbg.setSxsl(0);
zjbg.setFssl(0);
zjbg.setSxl(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
}
}
return zjbg;
}
}
最后,新建/report/chart.jsp生成曲线图如下:
<%@ page contentType="text/html;charset=GBK"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>

<%@ page import="java.awt.*,java.text.SimpleDateFormat,javax.swing.JPanel,org.jfree.chart.ChartFactory,org.jfree.chart.ChartPanel,org.jfree.chart.JFreeChart,org.jfree.chart.axis.DateAxis,org.jfree.chart.plot.XYPlot,org.jfree.chart.renderer.xy.XYItemRenderer,org.jfree.chart.renderer.xy.XYLineAndShapeRenderer,org.jfree.data.time.*,org.jfree.data.time.TimeSeries,org.jfree.data.time.TimeSeriesCollection,org.jfree.data.xy.XYDataset"%>
<%@ page import="org.jfree.chart.servlet.ServletUtilities,org.jfree.chart.axis.NumberAxis,org.jfree.chart.axis.ValueAxis"%>
<%@ page import="org.jfree.chart.axis.DateTickUnit"%>
<%@ page import = "org.jfree.ui.RectangleInsets,org.jfree.chart.title.TextTitle,java.text.NumberFormat"%>
<%@ page import = "java.util.ArrayList,com.wanglihu.vo.Zjbg,java.util.List,com.wanglihu.dao.ZjbgDAO,org.jfree.chart.labels.StandardPieToolTipGenerator,org.jfree.chart.axis.DateTickMarkPosition,java.sql.*,java.util.Iterator,java.util.Date,org.jfree.chart.title.LegendTitle,org.jfree.chart.axis.NumberTickUnit"%>
<%
List<Zjbg> list=(ArrayList)request.getAttribute("ZJBGLIST");
if(list!=null&&list.size()>0){ %>
<%
String startTime=(String)request.getAttribute("STARTTIME");
String endTime=(String)request.getAttribute("ENDTIME");
int startyears=Integer.parseInt(startTime.substring(0,4));
int startmonths=Integer.parseInt(startTime.substring(5,7));
int startdays=Integer.parseInt(startTime.substring(8,10));
String startYearAndMonthAndDay=startyears+"年"+startmonths+"月"+startdays+"日";
int endyears=Integer.parseInt(endTime.substring(0,4));
int endmonths=Integer.parseInt(endTime.substring(5,7));
int enddays=Integer.parseInt(endTime.substring(8,10));
String endYearAndMonthAndDay=endyears+"年"+endmonths+"月"+enddays+"日";
Iterator<Zjbg> iterator=list.iterator();
//设置曲线
TimeSeries mytimeseries = new TimeSeries("失效率",Day.class);
//从数据库中取值,数据和时间
while(iterator.hasNext()){
double sxl=0D;
Zjbg zjbg=iterator.next();
String zxsj=zjbg.getZxsj();
sxl=zjbg.getSxl();
//从yyyy-MM-dd
int year=Integer.parseInt(zxsj.substring(0,4));
int month=Integer.parseInt(zxsj.substring(5,7));
int day=Integer.parseInt(zxsj.substring(8,10));
mytimeseries.add(new Day(day,month,year),sxl);
}
//连接曲线
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(mytimeseries);
//x轴上的刻度点默认为时间段,设为true时代表的是时间点
dataset.setDomainIsPointsInTime(true);
String domain="("+startYearAndMonthAndDay+"-->"+endYearAndMonthAndDay+")"+"失效率之曲线图";
//设置曲线图
XYDataset xydataset = (XYDataset) dataset;
JFreeChart chart = ChartFactory.createTimeSeriesChart("",           //图表标题
  "报告执行时间", //目录轴的显示标签
  "失效率",      //数值轴的显示标签
  xydataset,    //数据集
  true,         //是否显示图例
  true,         //是否生成工具
  false );      //是否生成url链接
//设置图表对象的标题
chart.setTitle(new TextTitle(domain,new Font("幼圆",Font.PLAIN,24)));
//设置曲线图背景色
chart.setBackgroundPaint(Color.DARK_GRAY);//.decode("#98B6E8")
//取得统计图表的第一个图例
LegendTitle legend=chart.getLegend(0);
//修改图例的字体
legend.setItemFont(new Font("方正舒体",Font.HANGING_BASELINE,14));
//取得时间顺序图的Plot对象,即来得到所有数据点的集合
XYPlot plot = (XYPlot) chart.getPlot();
//取得X轴
DateAxis  categoryAxis =(DateAxis)plot.getDomainAxis();
//是否显示正向箭头
categoryAxis.setPositiveArrowVisible(true);
//x轴单位间隔为1天
categoryAxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,1));
//设置横轴显示标签的字体,坐标轴标题字体
categoryAxis.setLabelFont(new Font("隶书",Font.BOLD,18));
SimpleDateFormat format1 = new SimpleDateFormat("dd日");
//设置x轴数据单位以×月×日方式显示
categoryAxis.setDateFormatOverride(format1);
//取得Y轴
NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();
//设置纵轴显示标签的字体
numberAxis.setLabelFont(new Font("隶书",Font.BOLD,18));
//y轴单位间隔为2%
numberAxis.setTickUnit(new NumberTickUnit(0.02D));
//是否显示正向箭头
numberAxis.setPositiveArrowVisible(true);
//设置y轴以百分比方式显示
NumberFormat format =NumberFormat.getPercentInstance();
numberAxis.setNumberFormatOverride(format);
//数据轴上的显示最小值5%
numberAxis.setLowerBound(-0.050D);


XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
//设置曲线是否显示数据点
xylineandshaperenderer.setBaseShapesVisible(false);
//设置第一条曲线数据点填充为红色,如果一个图表有多条曲线可分别设置
xylineandshaperenderer.setSeriesFillPaint(0, Color.YELLOW);
//设置网格背景颜色
plot.setBackgroundPaint(Color.black);
//设置网格竖线颜色
plot.setDomainGridlinePaint(Color.green);
//设置网格横线颜色
plot.setRangeGridlinePaint(Color.green);
//设置曲线图与xy轴的距离,即曲线与xy轴贴近的距离
plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 0D));
String filename = ServletUtilities.saveChartAsPNG(chart, 820, 520, null, session);
String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + filename;

%>

<img src="<%= graphURL %>" border=0 usemap="#<%= filename %>">
<%} %>

之此,没有将DataBase.java的类贴上来,这是一个完成与数据库连接的类,每个人可以根据自己的实际情况设计此类,另外,本人将本实例所用到的PopupCalendar.js文件和jFreeChart.jar等jar包提供给读者下载使用。

你可能感兴趣的:(数据结构,oracle,sql,struts,jfreechart)