- 浏览: 529 次
-
最新评论
收藏列表
- 全部 [175]
- 默认 [46]
- jython [1]
- java泛型编程 [1]
- js正则表达式详解 [1]
- jdbc连接数据库 [1]
- 数据库连接池配置 [1]
- struts.xml [1]
- java读取xml文件 [1]
- java文件读写操作 [1]
- http://china-pub2010.iteye.com/blog/1413544 [1]
- java连接sql server数据库 [1]
- java连接sql server数据库2 [1]
- web.xml中配置404错误页面 [1]
- 自己的java读取xml文件-采用jdom技术 [1]
- 自己写的java读取xml文件-采用jdom技术-2 [1]
- 自己写的java读取xml文件-采用jdom技术-3 [1]
- js 解析xml文件实现省市级联下拉菜单 [1]
- frame框架的应用 [1]
- frame框架的应用2 [1]
- html 第六章 css + div实现整体布局 [1]
- 为div添加滚动条 博客分类: css [1]
- 布局管理 [1]
- java 连接各种数据库 [1]
- 自己的xml_dtree树形菜单的实现 [1]
- spring连接池配置详解 [1]
- spring连接池配置详解2 [1]
- spring连接池配置详解3 [1]
- hibernate数据库连接池配置 [1]
- tomcat配置数据库连接池 [1]
- tomcat配置数据库连接池2 [1]
- commons-fileupload工具的api与开发实例解析(一) [1]
- 利用 commons-fileupload 实现文件上传 [1]
- apache common fileupload api 详解 [1]
- 用java生成word文档 [1]
- java读取与写入excel文件 [1]
- java读写word文档2 [1]
- java poi word 写文档 [1]
- 实现jxl读取excel的demo实例 [1]
- 使用jacob来处理word文档—jacob的使用及下载安装 [1]
- java读取word文档-3 [1]
- js正则表达式访问网址 [1]
- 正则表达式笔记 [1]
- js正则表达式 2 [1]
- javascript与jquery 控制表格行的字体与背景色 [1]
- 给奇偶行分别设置不同的背景色 [1]
- strtus2通常情况下使用以下两种方式来访问上述三种对象,即servlet api解藕和耦合的访问方式。 [1]
- hibernate批处理 hibernatejdbc [2]
- 自己的jquery-dialog [1]
- struts2 上传文件大小设置 [2]
- struts2 上传文件类型限制 [1]
- jquery 异步提交表单并弹出提示结果信息 [1]
- 超级链接中的target关键字 [1]
- 自己的jquery 异步提交表单并弹出提示结果信息22 [1]
- struts2 ognl表达式的应用 [1]
- hibernate批处理2 [1]
- jquery easyui 操作总结 [1]
- jquery 操作总结 [1]
- jmail 简单应用 [1]
- struts2 文件下载 [1]
- 网页上的表格边框设计更多效果变化 [1]
- struts2文件下载 12 [1]
- 部件表与新物料认证表的关联关系 [1]
- js正则表达式验证数字 [1]
- 自己的hibernate批处理 [1]
- hibernate批处理pojo类 [1]
- hibernate批处理action [1]
- newmateappbilldaoimpl.java [1]
- dqdocumentdaoimpl.java [1]
- dqassemblydaoimpl.java [1]
- 文件上传action [1]
- 文件下载action [1]
- 文件下载页面 [1]
- 从word模板生成word文件 [1]
- <s:action>标签的使用 [1]
- 单元测试-junit [1]
- 单元测试-junit-dao层 [1]
- 监听器的创建 [1]
- holdpuke_1 [1]
- holdpuke_2 [1]
- holdpuke_3 [1]
- holdpuke_4 [1]
- holdpuke_5 [1]
- holdpuke_6 [1]
- holdpuke_7 [1]
- holdpuke_8 [1]
- jython-2 [1]
- jython_3 [1]
- 自定义标签和标签库函数的学习--自己的demo [1]
- 自定义标签和标签库函数的学习 [1]
- 手动编译java文件 [1]
- jquery_demo_1 [1]
- jquery批量文件上传 [1]
- 重写hashcode方法和equals方法demo [1]
- 重写hashcode方法和equals方法demo2 [1]
- 重写hashcode和equals方法2 [1]
- java web定时任务 [1]
- java异地备份 [1]
- linux上部署java web应用 [1]
- 异地备份2 [1]
- java读写文件如何避免中文乱码 [1]
- system.data.sqlclient.sqlerror: 备份集中的数据库备份与现有的 'xxx' 数据库不同 [1]
- sql server 日期操作 [1]
- 用java 程序实现二进制像十进制转化 或十进制转化为二进制 [1]
- sql server 2005 及以上版本的sql分页查询 [1]
- sql server 2005-----sql语句分页sql [1]
- sql中的日期操作 [1]
- dwr demo [1]
- 我的校验码生成技术--demo [1]
- log4j--demo [1]
- license系统功能介绍 [1]
- java枚举类型的使用--demo [1]
- 自己的文件批量压缩demo [1]
- java调用mysql存储过程的简单示例 [1]
- jfreechart报表技术的原理简述: [1]
- 多线程demo--生产者与消费者 [1]
- uploadify传参解决方法 [1]
- svn服务器的配置 [1]
- birtdemo.rptdesign文件01 [1]
- birtdemo.rptdesign文件02 [1]
- 获取birt报表引擎对象 [1]
- http://www.iteye.com/topic/611837 [1]
- 表单校验checkform [1]
- html5 canvas平移-示例 [1]
- html5拖动单个图标 [1]
- div拖动、平移 [1]
- 禁用鼠标点击事件 [1]
- 自己实现的下拉多选框 [1]
- idea中tomcat启动时报内存溢出问题处理 [1]
标题 | 标签 | 来源 | |
centeros7配置nginx为https证书 | |||
--查找nginx whereis nginx nginx 启动 systemctl start nginx 停止 systemctl stop nginx 重启 systemctl restart nginx --查找文件 find / -name 'webapp.conf' /bin/systemctl restart nginx.service centos7 生成ssl证书,搭建https地址 https://blog.csdn.net/qq_22385935/article/details/91990876 |
|||
java分库分表实现 | https://gitee.com/fengyuduke/my_open_resources/blob/master/sharding-jdbc-manualConfiguration.rar | ||
https://gitee.com/fengyuduke/my_open_resources/blob/master/sharding-jdbc-manualConfiguration.rar |
|||
nginx+tomcat负载均衡设置 | |||
参考:https://www.cnblogs.com/foxting/p/7993869.html |
|||
js回调函数的使用 | |||
<!DOCTYPE html> <html> <head> <title>js回调函数的使用</title> <script type="text/javascript"> function getInput(options, successcallback, errorcallback){ //确保callback是一个函数 if(typeof successcallback === "function"){ //调用它,既然我们已经确定了它是可调用的 var res = {}; res.username = options.username; res.classname = "高一1班"; successcallback(res); }else if (typeof errorcallback == "function"){ errorcallback("出错了"); } } function success(data) { alert("欢迎"+data.classname+":"+data.username); } function error(msg){ alert(msg); } getInput({username:"张珊"}, success, error); </script> </head> <body> </body> </html> |
|||
Birt + SSH2 完整实践11 | |||
http://www.blogjava.net/SpartaYew/archive/2011/05/19/350618.html |
|||
Birt + SSH2 完整实践 | http://www.blogjava.net/SpartaYew/archive/2011/05/19/350618.html | ||
Birt + SSH2 完整实践 |
|||
birt集成web项目 | http://www.bubuko.com/infodetail-575071.html | ||
http://www.bubuko.com/infodetail-575071.html |
|||
自定义分页插件:paging.js | |||
/*自定义分页工具栏插件:paging.js*/ (function($){ $.fn.itemPage = function(options){ var defaults = {}; var options = $.extend(defaults, options); var data=options.data,//数据 currpage=options.currpage,//当前页 pagesize=options.pagesize;//每页显示的数据条目器 var total=data.total; var items=$("<div id='items'></div>"), pagectrl=$("<div id='page_ctrl'></div>"); var first=$("<div id=\"first\" class=\"page_ctrl\" onClick=\"showPage('first')\">首页</div>"), prev=$("<div id=\"prev\" class=\"page_ctrl\" onClick=\"showPage('prev')\">上一页</div>"), currPageVal=$("<div class=\"page_ctrl\" style=\"width:auto;background-color:white;\">"+currpage+"</div>"), next=$("<div id=\"next\" class=\"page_ctrl\" onClick=\"showPage('next')\">下一页</div>"), last=$("<div id=\"last\" class=\"page_ctrl\" onClick=\"showPage('last')\">尾页</div>"), pageSelectText=$("<div class=\"page_ctrl\" style='width:60px;background-color:white;'>每页显示</div>"), pageSelect=$("<div id=\"pageSelect\" class=\"page_ctrl\" style='float:left;width:auto;background-color:white;'>"+ "<select id=\"pageSize\">"+ "<option value=\""+pagesize+"\">"+pagesize+"</option>"+ "<option value=\"10\">10</option>"+ "</select>"+ "</div>"), totalPageText=$("<div class=\"page_ctrl\" style=\"width:auto;background-color:white;\">共"+total+"条记录</div>"); var start=getStartindex(), end=getEndindex(); pagectrl.append(pageSelectText), pagectrl.append(pageSelect), pagectrl.append(totalPageText), pagectrl.append(first), pagectrl.append(prev), pagectrl.append(currPageVal), pagectrl.append(next), pagectrl.append(last); var container = $(this); container.append(pagectrl); function getStartindex(){ return (currpage-1)*pagesize; } function getEndindex(){ var endIndex=0; if(data.total%pagesize!=0 && currpage==getLastPage()){ endIndex = data.total; } else { endIndex = currpage*pagesize; } return endIndex; } showItemInfo = function(i){ console.log(i); }; }; })(jQuery); |
|||
利用反射实现类的动态加载-2 | |||
//利用反射实现类的动态加载-2 /* 5.SaleListController.java */ package com.hp.controller; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import java.util.Properties; import com.hp.service.SaleListService; public class SaleListController { public String execute(){ String params = "20000"; //页面传过来的参数 //通过标志位的值去查找配置文件className.properties try{ Properties p = new Properties(); String path = this.getClass().getResource("/com/hp/properties/className.properties").getPath(); InputStream fis = new FileInputStream(path); p.load(fis); String res = p.getProperty(params); fis.close(); return res; }catch(Exception e){ e.printStackTrace(); return "00000"; } } public void handler(){ String result = execute(); String className = "com.hp.service.impl."+result; try{ Class c = Class.forName(className); SaleListService instance = (SaleListService)c.newInstance(); List list = instance.getList(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) { SaleListController saleList = new SaleListController(); saleList.handler(); } } |
|||
利用反射实现类的动态加载-1 | |||
//利用反射实现类的动态加载-1 /* 1. SaleListService.java */ package com.hp.service; import java.util.List; public interface SaleListService { public List getList(); } /* 2. ASaleListServiceImpl.java */ package com.hp.service.impl; import java.util.List; import com.hp.service.SaleListService; public class ASaleListServiceImpl implements SaleListService{ public List getList() { System.out.println("返回销售清单A的List..."); return null; } } /* 3. BSaleListServiceImpl.java */ package com.hp.service.impl; import java.util.List; import com.hp.service.SaleListService; public class BSaleListServiceImpl implements SaleListService{ public List getList() { System.out.println("返回销售清单B的List..."); return null; } } #4.className.properties放在包com.hp.properties中 #这里配置接口的实现类 #销售清单A 10000=ASaleListServiceImpl #销售清单B 20000=BSaleListServiceImpl |
|||
linux连接工具和hibernate中的Query查询的参数设置新方式 | |||
hibernate中的Query查询的参数设置新方式: String uid = "s123"; String sql = "select * from tb_user where userid = :userId"; Query query = SessionFactory.getSession().createQuery(sql); query.setParameter("userId", uid); List list = query.list(); String loginUserId = "s221"; String sql = "select r.rolename, d.deptname "+ "from tb_role r , tb_dept d "+ "where r.userid = :userid and d.userid = :userid"; Query query = SessionFactory.getSession().createQuery(sql); query.setParameterList("userId", loginUserId); List list = query.list(); ----------------------------------------- linux连接工具:Xmanager |
|||
7.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第七部分) | |||
7.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第七部分) <detail> <row id="191"> <property name="style">column-style</property> <property name="textAlign">center</property> <property name="verticalAlign">middle</property> <property name="height">0.3645833333333333in</property> <cell id="193"> <property name="style">column-cell</property> <data id="242"> <property name="style">column-font</property> <structure name="dateTimeFormat"> <property name="category">Custom</property> <property name="pattern">yyyy-MM-dd HH:mm:ss</property> </structure> <property name="resultSetColumn">recv_time</property> </data> </cell> <cell id="196"> <property name="style">column-cell</property> <data id="245"> <property name="style">column-font</property> <property name="resultSetColumn">od_state</property> </data> </cell> <cell id="198"> <property name="style">column-cell</property> <data id="247"> <property name="style">column-font</property> <property name="resultSetColumn">totalCount</property> </data> </cell> <cell id="200"> <property name="style">column-cell</property> <data id="249"> <property name="style">column-font</property> <property name="resultSetColumn">doneCount</property> </data> </cell> <cell id="201"> <property name="style">column-cell</property> <data id="250"> <property name="style">column-font</property> <list-property name="highlightRules"> <structure> <property name="operator">eq</property> <property name="fontSize">16pt</property> <property name="color">#FF0000</property> <expression name="testExpr" type="javascript">row["doneRate"]</expression> <simple-property-list name="value1"> <value type="javascript">"-"</value> </simple-property-list> </structure> </list-property> <property name="resultSetColumn">doneRate</property> </data> </cell> </row> </detail> </table> </body> </report> |
|||
6.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第六部分) | |||
6.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第六部分) <header> <row id="178"> <property name="style">header-style</property> <property name="fontFamily">"微软雅黑"</property> <property name="fontWeight">bold</property> <property name="verticalAlign">middle</property> <property name="height">0.5104166666666666in</property> <cell id="180"> <property name="style">header-cell</property> <text id="230"> <property name="style">header-font</property> <property name="contentType">auto</property> <text-property name="content"><![CDATA[处理时间]]></text-property> </text> </cell> <cell id="183"> <property name="style">header-cell</property> <text id="233"> <property name="style">header-font</property> <property name="contentType">auto</property> <text-property name="content"><![CDATA[值班状态]]></text-property> </text> </cell> <cell id="185"> <property name="style">header-cell</property> <text id="235"> <property name="style">header-font</property> <property name="contentType">auto</property> <text-property name="content"><![CDATA[总数 (个)]]></text-property> </text> </cell> <cell id="187"> <property name="style">header-cell</property> <text id="237"> <property name="style">header-font</property> <property name="contentType">auto</property> <text-property name="content"><![CDATA[已处理个数 (个)]]></text-property> </text> </cell> <cell id="188"> <property name="style">header-cell</property> <text id="238"> <property name="style">header-font</property> <property name="contentType">auto</property> <text-property name="content"><![CDATA[处理率 (%)]]></text-property> </text> </cell> </row> </header> |
|||
5.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第五部分) | |||
5.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第五部分) <structure> <property name="name">doneRate</property> <text-property name="displayName">doneRate</text-property> <expression name="expression" type="javascript">var onetDoneRateRes; if(dataSetRow["totalCount"] == 0){ onetDoneRateRes = "-"; }else{ onetDoneRateRes = dataSetRow["doneRate"]; } onetDoneRateRes;</expression> <property name="dataType">javaObject</property> <property name="allowExport">true</property> </structure> <structure> <property name="name">avgTime</property> <text-property name="displayName">avgTime</text-property> <expression name="expression" type="javascript">var oneTktAvgTime; if(dataSetRow["totalCount"] == 0){ oneTktAvgTime = "-"; }else{ oneTktAvgTime = dataSetRow["avgTime"]; } oneTktAvgTime</expression> <property name="dataType">javaObject</property> <property name="allowExport">true</property> </structure> </list-property> <column id="218"> <property name="width">1.6354166666666667in</property> </column> <column id="221"> <property name="width">0.90625in</property> </column> <column id="223"> <property name="width">1.2916666666666667in</property> </column> <column id="225"> <property name="width">1.21875in</property> </column> <column id="226"> <property name="width">1.25in</property> </column> |
|||
4.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第四部分) | |||
4.birt报表在spring控制器中的应用示例demo-3(demo.rptdesign文件第四部分) <body> <table id="177"> <property name="width">100%</property> <property name="dataSet">oneticketScriptDataCollection</property> <list-property name="boundDataColumns"> <structure> <property name="name">recv_time</property> <text-property name="displayName">recv_time</text-property> <expression name="expression" type="javascript">dataSetRow["recv_time"]</expression> <property name="dataType">date-time</property> </structure> <structure> <property name="name">od_state</property> <text-property name="displayName">od_state</text-property> <expression name="expression" type="javascript">dataSetRow["od_state"]</expression> <property name="dataType">string</property> </structure> <structure> <property name="name">totalCount</property> <text-property name="displayName">totalCount</text-property> <expression name="expression" type="javascript">dataSetRow["totalCount"]</expression> <property name="dataType">integer</property> </structure> <structure> <property name="name">doneCount</property> <text-property name="displayName">doneCount</text-property> <expression name="expression" type="javascript">dataSetRow["doneCount"]</expression> <property name="dataType">integer</property> </structure> |
|||
3. birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第三部分) | |||
3. birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第三部分) <styles> <style name="report" id="4"> <property name="fontFamily">sans-serif</property> <property name="fontSize">10pt</property> </style> <style name="crosstab-cell" id="5"> <property name="borderBottomColor">#CCCCCC</property> <property name="borderBottomStyle">solid</property> <property name="borderBottomWidth">1pt</property> <property name="borderLeftColor">#CCCCCC</property> <property name="borderLeftStyle">solid</property> <property name="borderLeftWidth">1pt</property> <property name="borderRightColor">#CCCCCC</property> <property name="borderRightStyle">solid</property> <property name="borderRightWidth">1pt</property> <property name="borderTopColor">#CCCCCC</property> <property name="borderTopStyle">solid</property> <property name="borderTopWidth">1pt</property> </style> <style name="crosstab" id="6"> <property name="borderBottomColor">#CCCCCC</property> <property name="borderBottomStyle">solid</property> <property name="borderBottomWidth">1pt</property> <property name="borderLeftColor">#CCCCCC</property> <property name="borderLeftStyle">solid</property> <property name="borderLeftWidth">1pt</property> <property name="borderRightColor">#CCCCCC</property> <property name="borderRightStyle">solid</property> <property name="borderRightWidth">1pt</property> <property name="borderTopColor">#CCCCCC</property> <property name="borderTopStyle">solid</property> <property name="borderTopWidth">1pt</property> </style> </styles> <page-setup> <simple-master-page name="NewSimpleMasterPage" id="7"/> </page-setup> |
|||
2. birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第二部分) | |||
2. birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第二部分) <structure name="cachedMetaData"> <list-property name="resultSet"> <structure> <property name="position">2</property> <property name="name">recv_time</property> <property name="dataType">date-time</property> </structure> <structure> <property name="position">5</property> <property name="name">od_state</property> <property name="dataType">string</property> </structure> <structure> <property name="position">7</property> <property name="name">totalCount</property> <property name="dataType">integer</property> </structure> <structure> <property name="position">9</property> <property name="name">doneCount</property> <property name="dataType">integer</property> </structure> <structure> <property name="position">10</property> <property name="name">doneRate</property> <property name="dataType">float</property> </structure> <structure> <property name="position">11</property> <property name="name">avgTime</property> <property name="dataType">float</property> </structure> </list-property> </structure> <property name="dataSource">oneticketScriptDatasource</property> <method name="open"><![CDATA[count = 0; oneticketListBean = listBean;]]></method> <method name="fetch"><![CDATA[if(count < oneticketListBean.size()){ row["recv_time"] = oneticketListBean.get(count).getRecv_time(); if("2".equals(oneticketListBean.get(count).getOd_state())){ row["od_state"] = "已完成"; } row["totalCount"] = oneticketListBean.get(count).getTotalCount(); if(null == oneticketListBean.get(count).getTotalCount()){ row["totalCount"] = 0; } row["doneCount"] = oneticketListBean.get(count).getDoneCount(); if(null == oneticketListBean.get(count).getDoneCount()){ row["doneCount"] = 0; } row["doneRate"] = oneticketListBean.get(count).getDoneRate(); if(null == oneticketListBean.get(count).getDoneRate()){ row["doneRate"] = 100; } count++; return true; } return false;]]></method> </script-data-set> </data-sets> |
|||
birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第一部分) | |||
1. birt报表在spring控制器中的应用示例demo-2(demo.rptdesign文件第一部分) <?xml version="1.0" encoding="UTF-8"?> <report xmlns="http://www.eclipse.org/birt/2005/design" version="3.2.23" id="1"> <property name="createdBy">Eclipse BIRT 设计器 V4.4.0.v201405191524 构建 <4.4.0.v20140606-1451></property> <property name="units">in</property> <property name="iconFile">/templates/blank_report.gif</property> <property name="layoutPreference">auto layout</property> <property name="bidiLayoutOrientation">ltr</property> <property name="imageDPI">96</property> <list-property name="cssStyleSheets"> <structure> <property name="fileName">/reports/css/epms.css</property> <property name="useExternalCss">true</property> <property name="externalCssURI">/reports/css/epms.css</property> </structure> </list-property> <data-sources> <script-data-source name="oneticketScriptDatasource" id="8"/> </data-sources> <data-sets> <script-data-set name="oneticketScriptDataCollection" id="9"> <list-property name="resultSetHints"> <structure> <property name="position">1</property> <property name="name">recv_time</property> <property name="dataType">date-time</property> </structure> <structure> <property name="position">4</property> <property name="name">od_state</property> <property name="dataType">string</property> </structure> <structure> <property name="position">6</property> <property name="name">totalCount</property> <property name="dataType">integer</property> </structure> <structure> <property name="position">8</property> <property name="name">doneCount</property> <property name="dataType">integer</property> </structure> <structure> <property name="position">9</property> <property name="name">doneRate</property> <property name="dataType">float</property> </structure> <structure> <property name="position">10</property> <property name="name">avgTime</property> <property name="dataType">float</property> </structure> </list-property> <list-property name="columnHints"> <structure> <property name="columnName">recv_time</property> </structure> <structure> <property name="columnName">od_state</property> </structure> <structure> <property name="columnName">totalCount</property> </structure> <structure> <property name="columnName">doneCount</property> </structure> <structure> <property name="columnName">doneRate</property> </structure> <structure> <property name="columnName">avgTime</property> </structure> </list-property> |
|||
birt报表在spring控制器中的应用示例demo | |||
/**查询报表数据*/ @RequestMapping(method=RequestMethod.GET, value="/queryData") @ResponseBody public void queryData(HttpServletRequest request , HttpServletResponse response) { IRunAndRenderTask task = null; getGanmovstaService(); ServletContext sc = request.getSession().getServletContext(); String reportFile = "reports/user/user_report.rptdesign"; // 显示到报表的list int pageCurrent = 1; //当前页 int pageRecord = 10; //每页显示总记录数 //查询相应的统计数据 try{ reportFile = sc.getRealPath(reportFile); initReportEngine(sc); design = reportEngine.openReportDesign(reportFile); task = reportEngine.createRunAndRenderTask(design); List<UserPojo> ondutyList = userService.queryGanmovstaData(pageCurrent, pageRecord); task.addScriptableJavaObject("listBean", ondutyList); HTMLRenderOption option = new HTMLRenderOption(); option.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML); option.setOutputStream(response.getOutputStream()); task.setRenderOption(option); task.run(); }catch(IOException e){ log.error("Io异常", e); }catch(EngineException e){ log.error("报表引擎异常", e); }finally{ if(task != null){ task.close(); } } } /**导出报表*/ @RequestMapping(method = RequestMethod.GET, value = "/ganmovstaRepExport") @ResponseBody public void ganmovstaRepExport(HttpServletRequest request,HttpServletResponse response){ String pageNum = "1"; int pageRecord = userService.serachPage("1"); //总记录数 IRunAndRenderTask task = null; ServletContext sc = request.getSession().getServletContext(); initReportEngine(sc); //显示到报表的list List<UserPojo> ondutyList = null; getGanmovstaService(); try{ allList = userService.queryGanmovstaData(pageNum, pageRecord); }catch(Exception e){ log.error(e.getMessage()); } //查询相应的统计数据 String fname = "reports/user/user_report.rptdesign"; String reportFile = sc.getRealPath(fname); try{ initReportEngine(sc); design = reportEngine.openReportDesign(reportFile); task = reportEngine.createRunAndRenderTask(design); // 返回报表实体列表 task.addScriptableJavaObject("listBean", allList); //生成的目标文件 String fileName = "reports/user/user_report_des" + "." + ExportFormat.FORMAT_EXCEL; response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); RenderOption option = new EXCELRenderOption(); option.setOutputFormat(ExportFormat.FORMAT_EXCEL); option.setOutputStream(response.getOutputStream()); task.setRenderOption(option); task.run(); response.flushBuffer(); }catch(IOException e){ log.error("Io异常", e); }catch(EngineException e){ log.error("报表引擎异常", e); }finally{ if(task != null){ task.close(); } } } |
|||
获取MAC地址 | |||
package com.birt.analysis; import java.io.InputStreamReader; import java.io.LineNumberReader; public class GetMacAddressUtil { /**读取本地MAC地址*/ public void getMacAddress(){ try{ String cmd = "cmd /c ipconfig /all"; Process p = Runtime.getRuntime().exec(cmd); InputStreamReader bis = new InputStreamReader(p.getInputStream()); LineNumberReader lnr = new LineNumberReader(bis); String s = null; while((s = lnr.readLine()) != null){ if(s.contains("物理地址")){ System.out.println(s); break; } } lnr.close(); bis.close(); p.destroy(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) { GetMacAddressUtil gau = new GetMacAddressUtil(); gau.getMacAddress(); } } |
|||
quartz使用 | |||
quartz使用 1. ScheduerJob.java package com.hp.job; /** * 定时任务: * 第一步:编写任务类 :该类为一个普通的类 */ public class ScheduerJob { public void dojob(){ System.out.println("执行任务中..."); } } 2.spring配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <!-- 第二步:配置作业类 这一步是关键步骤,声明一个MethodInvokingJobDetailFactoryBean, 有两个关键属性:targetObject指定任务类,targetMethod指定运行的方法 --> <bean id="jobme" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <bean class="com.hp.job.ScheduerJob"></bean> </property> <property name="targetMethod" value="dojob"></property> <property name="concurrent" value="false"></property><!-- 作业不并发调度 --> </bean> <!-- 第三步:配置触发器(即作业调度的触发方式) 1):SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次 --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="jobme"></property> <!-- 调度工厂实例化后,经过0秒开始执行调度 --> <property name="startDelay" value="0"></property> <!-- 每2秒调度一次 --> <property name="repeatInterval" value="2000"></property> </bean> <!-- 第三步:配置触发器(即作业调度的触发方式) 2):CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobme"></property> <!-- 每天12:00运行一次 --> <property name="cronExpression" value="0 0 12 * * ?" /> </bean> <!-- 第四步:配置调度工厂 --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger"></ref> </list> </property> </bean> </beans> quartz使用 |
|||
quartz使用 | |||
quartz使用 1. ScheduerJob.java package com.hp.job; /** * 定时任务: * 第一步:编写任务类 :该类为一个普通的类 */ public class ScheduerJob { public void dojob(){ System.out.println("执行任务中..."); } } 2.spring配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <!-- 第二步:配置作业类 这一步是关键步骤,声明一个MethodInvokingJobDetailFactoryBean, 有两个关键属性:targetObject指定任务类,targetMethod指定运行的方法 --> <bean id="jobme" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <bean class="com.hp.job.ScheduerJob"></bean> </property> <property name="targetMethod" value="dojob"></property> <property name="concurrent" value="false"></property><!-- 作业不并发调度 --> </bean> <!-- 第三步:配置触发器(即作业调度的触发方式) 1):SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次 --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="jobme"></property> <!-- 调度工厂实例化后,经过0秒开始执行调度 --> <property name="startDelay" value="0"></property> <!-- 每2秒调度一次 --> <property name="repeatInterval" value="2000"></property> </bean> <!-- 第三步:配置触发器(即作业调度的触发方式) 2):CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobme"></property> <!-- 每天12:00运行一次 --> <property name="cronExpression" value="0 0 12 * * ?" /> </bean> <!-- 第四步:配置调度工厂 --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger"></ref> </list> </property> </bean> </beans> |
|||
枚举用法3 | |||
package com.birt.analysis; /**枚举类型使用demo3 * 测试类 */ public class EnumDemo { public static void main(String[] args) { String[] names = {"orderNo" , "styleNo"}; for(int i = 0; i < names.length; i++){ SaleEnum s = SaleEnum.getSaleEnum(names[i]); switch(s){ case ORDERNO: System.out.println("print "+s.name); break; case STYLENO: System.out.println("print "+s.name); break; default: System.out.println("print null"); } } } } 2. package com.birt.analysis; /**枚举类型使用demo3 * 测试类 */ public class EnumDemo { public static void main(String[] args) { String[] names = {"orderNo" , "styleNo"}; for(int i = 0; i < names.length; i++){ SaleEnum s = SaleEnum.getSaleEnum(names[i]); switch(s){ case ORDERNO: System.out.println("print "+s.name); break; case STYLENO: System.out.println("print "+s.name); break; default: System.out.println("print null"); } } } } |
|||
birt (2) | |||
------------------------------ IRunAndRenderTask task = null; getGanmovstaService(); ServletContext sc = request.getSession().getServletContext(); String reportFileName = "reports/ganmovsta/ganmovsta_"; // 显示到报表的list String type = String.valueOf(GanmovstaConstant.ALL_COUNTTYPE); String startTime = ""; String endTime = ""; String param = request.getParameter("param"); //param为报表插件自动封装的一个参数名 JSONObject json = JSONObject.fromObject(param); int pageCurrent = changeFromStringToInt(json.get("page").toString(), GanmovstaConstant.PAGENUM); //当前页 int pageRecord = changeFromStringToInt(json.get("pageSize").toString(), GanmovstaConstant.PAGESIZE); //每页显示总记录数 type = json.get("qtype").toString(); String sId = json.get("sId").toString(); //查询相应的统计数据 try{ String reportFile = getReportFileName(reportFileName, type); reportFile = sc.getRealPath(reportFile); initReportEngine(sc); design = reportEngine.openReportDesign(reportFile); task = reportEngine.createRunAndRenderTask(design); startTime = json.get("startTime").toString().replaceAll("_", " "); endTime = json.get("endTime").toString().replaceAll("_", " "); if(String.valueOf(GanmovstaConstant.ALL_COUNTTYPE).equals(type)){ List<PmsOndutyDataBean> allList = ganmovstaService.queryAllGanmovstaData(sId, type, pageCurrent, pageRecord, startTime, endTime); //Integer.valueOf(pageSize) task.addScriptableJavaObject("listBean", allList); }else{ List<PmsOndutyDetailDataBean> ondutyList = ganmovstaService.queryGanmovstaData(sId, type, pageCurrent, pageRecord, startTime, endTime); task.addScriptableJavaObject("listBean", ondutyList); } HTMLRenderOption option = new HTMLRenderOption(); option.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML); option.setOutputStream(response.getOutputStream()); task.setRenderOption(option); task.run(); }catch(IOException e){ log.error("Io异常", e); }catch(EngineException e){ log.error("报表引擎异常", e); }finally{ if(task != null){ task.close(); } } |
|||
birt | |||
String qtype = request.getParameter("qtype"); String startTime = request.getParameter("startTime").replaceAll("_", " "); String endTime = request.getParameter("endTime").replaceAll("_", " "); String pageNum = "1"; //request.getParameter("page"); String pageSize = request.getParameter("pageSize"); int pageCurrent = changeFromStringToInt(pageNum, GanmovstaConstant.PAGENUM); int pageRecord = changeFromStringToInt(pageSize, GanmovstaConstant.PAGESIZE); String sId = (null == request.getParameter("sId") ? "" : request.getParameter("sId")) ; String[] params = {"","","",startTime,endTime,sId}; pageRecord = getGanmovstaService().serachPage(params); IRunAndRenderTask task = null; ServletContext sc = request.getSession().getServletContext(); initReportEngine(sc); //显示到报表的list List<PmsOndutyDataBean> allList = null; List<PmsOndutyDetailDataBean> ondutyList = null; getGanmovstaService(); try{ if(String.valueOf(GanmovstaConstant.ALL_COUNTTYPE).equals(qtype)){ allList = ganmovstaService.queryAllGanmovstaData(sId, qtype, pageCurrent, pageRecord, startTime, endTime); }else{ ondutyList = ganmovstaService.queryGanmovstaData(sId, qtype, pageCurrent, pageRecord, startTime, endTime); } }catch(Exception e){ log.error(e.getMessage()); } //查询相应的统计数据 String fname = getReportFileName("reports/ganmovsta/ganmovsta_", qtype); String reportFile = sc.getRealPath(fname); try{ initReportEngine(sc); design = reportEngine.openReportDesign(reportFile); task = reportEngine.createRunAndRenderTask(design); // 返回报表实体列表 if(String.valueOf(GanmovstaConstant.ALL_COUNTTYPE).equals(qtype)){ task.addScriptableJavaObject("listBean", allList); }else{ task.addScriptableJavaObject("listBean", ondutyList); } //fname的值reports/ganmovsta/ganmovsta_onduty_alarm.rptdesign int startIndex = fname.indexOf("ganmovsta_"); int endIndex = fname.indexOf("."); //生成的目标文件 String fileName = getFormatFileName(startTime, endTime, qtype) + "." + ExportFormat.FORMAT_EXCEL;//fname.substring(startIndex, endIndex)+"_"+System.currentTimeMillis()+"."+ExportFormat.FORMAT_EXCEL; //获取电站名称 String sName = getStationNameBySId(sId); fileName = sName + "_" + fileName; response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); RenderOption option = new EXCELRenderOption(); option.setOutputFormat(ExportFormat.FORMAT_EXCEL); option.setOutputStream(response.getOutputStream()); task.setRenderOption(option); task.run(); response.flushBuffer(); }catch(IOException e){ log.error("Io异常", e); }catch(EngineException e){ log.error("报表引擎异常", e); }finally{ if(task != null){ task.close(); } } |
|||
自己实现的简单的请假流程Demo(ssh_myworkflow)_1.1.0 | |||
1. applicationContext_action.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!--Action bean --> <!-- 给action添加scope属性用来避免spring创建单例,这样防止线程不安全 --> <!-- <bean id="dQDocumentAction" class="com.tdtech.pdm.create.action.DQDocumentAction" scope="prototype"> <property name="dQDocumentServiceImpl" ref="dQDocumentServiceImpl"></property> </bean> --> <bean id="deployFlowAction" class="com.hp.action.DeployFlowAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <bean id="userAction" class="com.hp.action.UserAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <bean id="roleAction" class="com.hp.action.RoleAction" scope="prototype"> <property name="roleService" ref="roleService"></property> </bean> <bean id="permissionAction" class="com.hp.action.PermissionAction" scope="prototype"> <property name="permissionService" ref="permissionService"></property> <property name="userService" ref="userService"></property> <property name="roleService" ref="roleService"></property> </bean> </beans> 2.applicationContext_dao.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 配置Dao层bean --> <bean id="userDao" class="com.hp.dao.impl.UserDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="roleDao" class="com.hp.dao.impl.RoleDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="permissionDao" class="com.hp.dao.impl.PermissionDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans> |
|||
修复bug的POI从模板生成excel文件--demo | |||
package com.excel.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import com.excel.pojo.ProductPojo; /** * 从模板生成excel文件的工具类 */ public class WriteExcelUtil{ private Workbook wb; /** * 生成目标文件的电子表格对象(即Workbook实例) * @param templateFile 模板文件 * @param desFile 目标文件 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 * @return Workbook类的对象 */ public Workbook getInstance(File templateFile, File desFile,Map<String, Object> map, Object[][] objs, Class<?> cls){ try { wb = WorkbookFactory.create(new FileInputStream(templateFile)); int i = 0; List<Sheet> sheets = new ArrayList<Sheet>(); while(true){ Sheet sheet = null; try{ sheet = wb.getSheetAt(i); if(sheet != null){ i++; sheets.add(sheet); }else{ break; } }catch(IllegalArgumentException ex){ break; } } System.out.println("size="+sheets.size()); for (Sheet sheet2 : sheets) { System.out.println("sheet name is "+sheet2.getSheetName()+" row number is "+sheet2.getLastRowNum()); int lastRowNum = sheet2.getLastRowNum(); this.handler(sheet2, lastRowNum,map, objs, cls); } } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } /** 该方法主要是取出当前Sheet页中的每一行的行对象,然后调用setCellValue()方法设置单元格的值 * @param sheet2 当前Sheet页对象 * @param lastRowNum 当前Sheet页的最后一行的行号,下标从0开始 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void handler(Sheet sheet2,int lastRowNum,Map<String, Object> map, Object[][] objs, Class<?> cls){ for(int r = 0; r <= lastRowNum; r++){ // System.out.println("行编号:"+(r+1)); Row row = sheet2.getRow(r); if(row != null) this.setCellValue(row,sheet2, r, map, objs, cls); } } /** 设置当前行的单元格的值 * @param row 当前行对象 * @param newSheet 当前Sheet对象即当前表格页对象 * @param r 当前行号 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void setCellValue(Row row, Sheet newSheet, int r,Map<String, Object> map, Object[][] objs, Class<?> cls){ Row rw = newSheet.getRow(r); int lastCellNum = row.getLastCellNum(); for(int c = 0; c <= lastCellNum; c++){ Cell cell = row.getCell(c); if(cell != null){ Cell ncell = rw.getCell(c); // if(cell.toString() != null || !"".equals(cell.toString())){ // System.out.println(cell.toString()); // } if(map != null && map.size() > 0){ if(cell.toString().startsWith("$")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ if(map.get(cell.toString()) instanceof BigDecimal){ ncell.setCellValue(((BigDecimal)map.get(cell.toString())).doubleValue()); } } }else if(cell.toString().startsWith("#")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ ncell.setCellValue(map.get(cell.toString()).toString()); } } } int c_old = c; if(objs.length > 0 && cell.toString().equals("datas")){ cell.setCellValue(""); // System.out.println("objs.length = "+objs.length); int cols = objs[0].length; for(int k = 0; k < cols; k++){ //行号 for(int m = 0; m < objs.length; m++){ //列号 System.out.println(objs[m][k]); } System.out.println("======================"); } for(int rn = 0; rn < cols; rn++){ // System.out.println("当前行号:"+rn+", 下一行行号: "+(rn+1)); Row nrw = newSheet.createRow(r++); //创建一行 Cell cellNew = null; for(int cn = 0; cn < objs.length; cn++){ // System.out.println("当前值="+objs[rn][cn].toString()); cellNew = nrw.createCell(c++); //创建一列 CellStyle cstyle = cellNew.getCellStyle(); if(objs[cn][rn] instanceof String){ cellNew.setCellValue(objs[cn][rn].toString()); cstyle.setAlignment(CellStyle.ALIGN_CENTER); }else if(objs[cn][rn] instanceof Integer){ cellNew.setCellValue((Integer)objs[cn][rn]); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[cn][rn] instanceof BigDecimal){ cellNew.setCellValue(((BigDecimal)objs[cn][rn]).doubleValue()); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[cn][rn] instanceof Double){ cellNew.setCellValue((Double)objs[cn][rn]); }else if(objs[cn][rn] instanceof Character){ cellNew.setCellValue((Character)objs[cn][rn]); }else if(objs[cn][rn] instanceof Boolean){ cellNew.setCellValue((Boolean)objs[cn][rn]); } } c = c_old; } break; } } } } /** * 将存放对象的list封装成Object二维数组 * @param list 存放持久层对象的list * @param ros 行数 * @param cols 列数 * @param cls 用于反射类使用 * @return Object[列号][行号] */ public Object[][] getObjectArr(List<?> list,final int ros, final int cols, Class<?> cls){ Object[][] objs = new Object[cols][ros]; //8行10列 Field[] fields = cls.getDeclaredFields(); for(int j = 0 ; j < cols; j++){ //列好 // System.out.println("----------------------"); for(int i = 0 ; i < ros; i++){ Object obj = list.get(i); try { Field field = cls.getDeclaredField(fields[j].getName()); // System.out.println("obj["+i+"]["+j+"] = "+field.get(obj).toString()); // System.out.println("print field "+fields[j].getName()+"="+field.get(obj).toString()); if(field.get(obj) == null || "".equals(field.get(obj).toString().trim())){ objs[j][i] = ""; }else if(field.get(obj) instanceof String){ objs[j][i] = ""+field.get(obj).toString(); }else if(field.get(obj) instanceof Integer){ objs[j][i] = (Integer)field.get(obj); }else if(field.get(obj) instanceof BigDecimal){ objs[j][i] = ((BigDecimal)field.get(obj)).doubleValue(); }else if(field.get(obj) instanceof Double){ objs[j][i] = (Double)field.get(obj); }else if(field.get(obj) instanceof Character){ objs[j][i] = (Character)field.get(obj); }else if(field.get(obj) instanceof Boolean){ objs[j][i] = (Boolean)field.get(obj); } //objs[j][i] = field.get(obj).toString(); } catch (SecurityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } // for(int k = 0; k < ros; k++){ //行号 // for(int m = 0; m < cols; m++){ //列号 // System.out.println(objs[m][k]); // } // System.out.println("======================"); // } return objs; } /** * 测试方法 * @param args * @throws FileNotFoundException * @throws IOException */ public static void main(String[] args) throws FileNotFoundException, IOException{ File file = new File("D:\\twx162737\\test\\quetoList.xlsx"); WriteExcelUtil ti = new WriteExcelUtil(); File desFile = new File("D:\\twx162737\\test\\mtest.xlsx"); if(desFile.exists()){ desFile.delete(); desFile.createNewFile(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("#contractName", "古镇唯美灯饰有限公司_HT20140826001"); map.put("$total", new BigDecimal(200000)); map.put("$equAndInsure", new BigDecimal(5000)); map.put("$engineerService", new BigDecimal(2000)); map.put("$maintainService", new BigDecimal(10000)); map.put("$oneFavourable", new BigDecimal(20000)); map.put("$contractedPrice", new BigDecimal(197000)); List<ProductPojo> list = new ArrayList<ProductPojo>(); ProductPojo pp = new ProductPojo(1,"HS-S21-D21-001","白炽灯","个",50,10.0,500.0,""); ProductPojo pp2 = new ProductPojo(2,"HS-S21-D21-002","台式灯","盏",100,100.0,10000.0,""); ProductPojo pp3 = new ProductPojo(3,"HS-S21-D21-003","路灯","盏",50,800.0,40000.0,""); ProductPojo pp4 = new ProductPojo(4,"HS-S21-D21-004","椰树灯","盏",100,2000.0,200000.0,""); ProductPojo pp5 = new ProductPojo(5,"HS-S21-D21-005","吊灯","盏",110,1000.0,110000.0,""); ProductPojo pp6 = new ProductPojo(6,"HS-S21-D21-006","白光灯","盏",100,20.0,2000.0,""); ProductPojo pp7 = new ProductPojo(7,"HS-S21-D21-007","日光灯","盏",80,50.0,4000.0,""); ProductPojo pp8 = new ProductPojo(8,"HS-S21-D21-008","节能灯","盏",60,60.0,3600.0,""); ProductPojo pp9 = new ProductPojo(9,"HS-S21-D21-009","节能灯s","盏",70,60.0,4200.0,""); ProductPojo pp10 = new ProductPojo(10,"HS-S21-D21-010","节能灯d","盏",60,60.0,3600.0,""); list.add(pp); list.add(pp2); list.add(pp3); list.add(pp4); list.add(pp5); list.add(pp6); list.add(pp7); list.add(pp8); list.add(pp9); list.add(pp10); Object[][] objs = ti.getObjectArr(list, list.size(), 8, ProductPojo.class); Workbook wb = ti.getInstance(file, desFile, map, objs , ProductPojo.class); FileOutputStream fos = new FileOutputStream(desFile); wb.write(fos); fos.flush(); fos.close(); } } 2. package com.excel.pojo; public class ProductPojo { public Integer id; public String pcode; public String pname; public String punit; public Integer pnumber; public Double pprice; public Double ptotal; public String premark; public ProductPojo() { } public ProductPojo(Integer id, String pcode, String pname, String punit, Integer pnumber, Double pprice, Double ptotal, String premark) { this.id = id; this.pcode = pcode; this.pname = pname; this.punit = punit; this.pnumber = pnumber; this.pprice = pprice; this.ptotal = ptotal; this.premark = premark; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPcode() { return pcode; } public void setPcode(String pcode) { this.pcode = pcode; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getPunit() { return punit; } public void setPunit(String punit) { this.punit = punit; } public Integer getPnumber() { return pnumber; } public void setPnumber(Integer pnumber) { this.pnumber = pnumber; } public Double getPprice() { return pprice; } public void setPprice(Double pprice) { this.pprice = pprice; } public Double getPtotal() { return ptotal; } public void setPtotal(Double ptotal) { this.ptotal = ptotal; } public String getPremark() { return premark; } public void setPremark(String premark) { this.premark = premark; } } |
|||
自己的POI从模板生成excel文件的demo | |||
package com.excel.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import com.excel.pojo.ProductPojo; /** * 从模板生成excel文件的工具类 */ public class WriteExcelUtil{ private Workbook wb; /** * 生成目标文件的电子表格对象(即Workbook实例) * @param templateFile 模板文件 * @param desFile 目标文件 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 * @return Workbook类的对象 */ public Workbook getInstance(File templateFile, File desFile,Map<String, Object> map, Object[][] objs, Class<?> cls){ try { wb = WorkbookFactory.create(new FileInputStream(templateFile)); int i = 0; List<Sheet> sheets = new ArrayList<Sheet>(); while(true){ Sheet sheet = null; try{ sheet = wb.getSheetAt(i); if(sheet != null){ i++; sheets.add(sheet); }else{ break; } }catch(IllegalArgumentException ex){ break; } } System.out.println("size="+sheets.size()); for (Sheet sheet2 : sheets) { System.out.println("sheet name is "+sheet2.getSheetName()+" row number is "+sheet2.getLastRowNum()); int lastRowNum = sheet2.getLastRowNum(); this.handler(sheet2, lastRowNum,map, objs, cls); } } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } /** 该方法主要是取出当前Sheet页中的每一行的行对象,然后调用setCellValue()方法设置单元格的值 * @param sheet2 当前Sheet页对象 * @param lastRowNum 当前Sheet页的最后一行的行号,下标从0开始 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void handler(Sheet sheet2,int lastRowNum,Map<String, Object> map, Object[][] objs, Class<?> cls){ for(int r = 0; r <= lastRowNum; r++){ // System.out.println("行编号:"+(r+1)); Row row = sheet2.getRow(r); if(row != null) this.setCellValue(row,sheet2, r, map, objs, cls); } } /** 设置当前行的单元格的值 * @param row 当前行对象 * @param newSheet 当前Sheet对象即当前表格页对象 * @param r 当前行号 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void setCellValue(Row row, Sheet newSheet, int r,Map<String, Object> map, Object[][] objs, Class<?> cls){ Row rw = newSheet.getRow(r); int lastCellNum = row.getLastCellNum(); for(int c = 0; c <= lastCellNum; c++){ Cell cell = row.getCell(c); if(cell != null){ Cell ncell = rw.getCell(c); // if(cell.toString() != null || !"".equals(cell.toString())){ // System.out.println(cell.toString()); // } if(map != null && map.size() > 0){ if(cell.toString().startsWith("$")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ if(map.get(cell.toString()) instanceof BigDecimal){ ncell.setCellValue(((BigDecimal)map.get(cell.toString())).doubleValue()); } } }else if(cell.toString().startsWith("#")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ ncell.setCellValue(map.get(cell.toString()).toString()); } } } int c_old = c; if(objs.length > 0 && cell.toString().equals("datas")){ cell.setCellValue(""); // System.out.println("objs.length = "+objs.length); for(int rn = 0; rn < objs.length; rn++){ // System.out.println("当前行号:"+rn+", 下一行行号: "+(rn+1)); Row nrw = newSheet.createRow(r++); //创建一行 Cell cellNew = null; for(int cn = 0; cn < objs[rn].length; cn++){ // System.out.println("当前值="+objs[rn][cn].toString()); cellNew = nrw.createCell(c++); //创建一列 CellStyle cstyle = cellNew.getCellStyle(); if(objs[rn][cn] instanceof String){ cellNew.setCellValue(objs[rn][cn].toString()); cstyle.setAlignment(CellStyle.ALIGN_CENTER); }else if(objs[rn][cn] instanceof Integer){ cellNew.setCellValue((Integer)objs[rn][cn]); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[rn][cn] instanceof BigDecimal){ cellNew.setCellValue(((BigDecimal)objs[rn][cn]).doubleValue()); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[rn][cn] instanceof Double){ cellNew.setCellValue((Double)objs[rn][cn]); }else if(objs[rn][cn] instanceof Character){ cellNew.setCellValue((Character)objs[rn][cn]); }else if(objs[rn][cn] instanceof Boolean){ cellNew.setCellValue((Boolean)objs[rn][cn]); } } c = c_old; } break; } } } } /** * 将存放对象的list封装成Object二维数组 * @param list 存放持久层对象的list * @param ros 行数 * @param cols 列数 * @param cls 用于反射类使用 * @return Object[][] */ public Object[][] getObjectArr(List<?> list,int ros, int cols, Class<?> cls){ Object[][] objs = new Object[cols][ros]; Field[] fields = cls.getDeclaredFields(); for(int i = 0 ; i < list.size(); i++){ Object obj = list.get(i); for(int j = 0 ; j < cols; j++){ try { Field field = cls.getDeclaredField(fields[j].getName()); // System.out.println("print field "+fields[j].getName()+"="+field.get(obj).toString()); if(field.get(obj) instanceof String){ objs[i][j] = field.get(obj).toString(); }else if(field.get(obj) instanceof Integer){ objs[i][j] = (Integer)field.get(obj); }else if(field.get(obj) instanceof BigDecimal){ objs[i][j] = ((BigDecimal)field.get(obj)).doubleValue(); }else if(field.get(obj) instanceof Double){ objs[i][j] = (Double)field.get(obj); }else if(field.get(obj) instanceof Character){ objs[i][j] = (Character)field.get(obj); }else if(field.get(obj) instanceof Boolean){ objs[i][j] = (Boolean)field.get(obj); } } catch (SecurityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } return objs; } /** * 测试方法 * @param args * @throws FileNotFoundException * @throws IOException */ public static void main(String[] args) throws FileNotFoundException, IOException{ File file = new File("D:\\test\\quetoList.xlsx"); WriteExcelUtil ti = new WriteExcelUtil(); File desFile = new File("D:\\test\\mtest.xlsx"); if(desFile.exists()){ desFile.delete(); desFile.createNewFile(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("#contractName", "古镇唯美灯饰有限公司_HT20140826001"); map.put("$total", new BigDecimal(200000)); map.put("$equAndInsure", new BigDecimal(5000)); map.put("$engineerService", new BigDecimal(2000)); map.put("$maintainService", new BigDecimal(10000)); map.put("$oneFavourable", new BigDecimal(20000)); map.put("$contractedPrice", new BigDecimal(197000)); List<ProductPojo> list = new ArrayList<ProductPojo>(); ProductPojo pp = new ProductPojo(1,"HS-S21-D21-001","白炽灯","个",50,10.0,500.0,""); ProductPojo pp2 = new ProductPojo(2,"HS-S21-D21-002","台式灯","盏",100,100.0,10000.0,""); ProductPojo pp3 = new ProductPojo(3,"HS-S21-D21-003","路灯","盏",50,800.0,40000.0,""); ProductPojo pp4 = new ProductPojo(4,"HS-S21-D21-004","椰树灯","盏",100,2000.0,200000.0,""); ProductPojo pp5 = new ProductPojo(5,"HS-S21-D21-005","吊灯","盏",110,1000.0,110000.0,""); ProductPojo pp6 = new ProductPojo(6,"HS-S21-D21-006","白光灯","盏",100,20.0,2000.0,""); ProductPojo pp7 = new ProductPojo(7,"HS-S21-D21-007","日光灯","盏",80,50.0,4000.0,""); ProductPojo pp8 = new ProductPojo(8,"HS-S21-D21-008","节能灯","盏",60,60.0,3600.0,""); list.add(pp); list.add(pp2); list.add(pp3); list.add(pp4); list.add(pp5); list.add(pp6); list.add(pp7); list.add(pp8); Object[][] objs = ti.getObjectArr(list, list.size(), 8, ProductPojo.class); Workbook wb = ti.getInstance(file, desFile, map, objs , ProductPojo.class); FileOutputStream fos = new FileOutputStream(desFile); wb.write(fos); fos.flush(); fos.close(); } } |
|||
自己的POI从模板生成excel文件-POI技术实现 | |||
package com.excel.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import com.excel.pojo.ProductPojo; /** * 从模板生成excel文件的工具类 */ public class WriteExcelUtil{ private Workbook wb; /** * 生成目标文件的电子表格对象(即Workbook实例) * @param templateFile 模板文件 * @param desFile 目标文件 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 * @return Workbook类的对象 */ public Workbook getInstance(File templateFile, File desFile,Map<String, Object> map, Object[][] objs, Class<?> cls){ try { wb = WorkbookFactory.create(new FileInputStream(templateFile)); int i = 0; List<Sheet> sheets = new ArrayList<Sheet>(); while(true){ Sheet sheet = null; try{ sheet = wb.getSheetAt(i); if(sheet != null){ i++; sheets.add(sheet); }else{ break; } }catch(IllegalArgumentException ex){ break; } } System.out.println("size="+sheets.size()); for (Sheet sheet2 : sheets) { System.out.println("sheet name is "+sheet2.getSheetName()+" row number is "+sheet2.getLastRowNum()); int lastRowNum = sheet2.getLastRowNum(); this.handler(sheet2, lastRowNum,map, objs, cls); } } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } /** 该方法主要是取出当前Sheet页中的每一行的行对象,然后调用setCellValue()方法设置单元格的值 * @param sheet2 当前Sheet页对象 * @param lastRowNum 当前Sheet页的最后一行的行号,下标从0开始 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void handler(Sheet sheet2,int lastRowNum,Map<String, Object> map, Object[][] objs, Class<?> cls){ for(int r = 0; r <= lastRowNum; r++){ // System.out.println("行编号:"+(r+1)); Row row = sheet2.getRow(r); if(row != null) this.setCellValue(row,sheet2, r, map, objs, cls); } } /** 设置当前行的单元格的值 * @param row 当前行对象 * @param newSheet 当前Sheet对象即当前表格页对象 * @param r 当前行号 * @param map 封装预设值标签的值 * @param objs 封装对象的Object[][]数组 * @param cls 用于反射类使用 */ public void setCellValue(Row row, Sheet newSheet, int r,Map<String, Object> map, Object[][] objs, Class<?> cls){ Row rw = newSheet.getRow(r); int lastCellNum = row.getLastCellNum(); for(int c = 0; c <= lastCellNum; c++){ Cell cell = row.getCell(c); if(cell != null){ Cell ncell = rw.getCell(c); // if(cell.toString() != null || !"".equals(cell.toString())){ // System.out.println(cell.toString()); // } if(map != null && map.size() > 0){ if(cell.toString().startsWith("$")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ if(map.get(cell.toString()) instanceof BigDecimal){ ncell.setCellValue(((BigDecimal)map.get(cell.toString())).doubleValue()); } } }else if(cell.toString().startsWith("#")){ if(cell.toString().equals(map.containsKey(cell.toString())==true?cell.toString():"")){ ncell.setCellValue(map.get(cell.toString()).toString()); } } } int c_old = c; if(objs.length > 0 && cell.toString().equals("datas")){ cell.setCellValue(""); // System.out.println("objs.length = "+objs.length); for(int rn = 0; rn < objs.length; rn++){ // System.out.println("当前行号:"+rn+", 下一行行号: "+(rn+1)); Row nrw = newSheet.createRow(r++); //创建一行 Cell cellNew = null; for(int cn = 0; cn < objs[rn].length; cn++){ // System.out.println("当前值="+objs[rn][cn].toString()); cellNew = nrw.createCell(c++); //创建一列 CellStyle cstyle = cellNew.getCellStyle(); if(objs[rn][cn] instanceof String){ cellNew.setCellValue(objs[rn][cn].toString()); cstyle.setAlignment(CellStyle.ALIGN_CENTER); }else if(objs[rn][cn] instanceof Integer){ cellNew.setCellValue((Integer)objs[rn][cn]); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[rn][cn] instanceof BigDecimal){ cellNew.setCellValue(((BigDecimal)objs[rn][cn]).doubleValue()); cstyle.setAlignment(CellStyle.ALIGN_RIGHT); }else if(objs[rn][cn] instanceof Double){ cellNew.setCellValue((Double)objs[rn][cn]); }else if(objs[rn][cn] instanceof Character){ cellNew.setCellValue((Character)objs[rn][cn]); }else if(objs[rn][cn] instanceof Boolean){ cellNew.setCellValue((Boolean)objs[rn][cn]); } } c = c_old; } break; } } } } /** * 将存放对象的list封装成Object二维数组 * @param list 存放持久层对象的list * @param ros 行数 * @param cols 列数 * @param cls 用于反射类使用 * @return Object[][] */ public Object[][] getObjectArr(List<?> list,int ros, int cols, Class<?> cls){ Object[][] objs = new Object[cols][ros]; Field[] fields = cls.getDeclaredFields(); for(int i = 0 ; i < list.size(); i++){ Object obj = list.get(i); for(int j = 0 ; j < cols; j++){ try { Field field = cls.getDeclaredField(fields[j].getName()); // System.out.println("print field "+fields[j].getName()+"="+field.get(obj).toString()); if(field.get(obj) instanceof String){ objs[i][j] = field.get(obj).toString(); }else if(field.get(obj) instanceof Integer){ objs[i][j] = (Integer)field.get(obj); }else if(field.get(obj) instanceof BigDecimal){ objs[i][j] = ((BigDecimal)field.get(obj)).doubleValue(); }else if(field.get(obj) instanceof Double){ objs[i][j] = (Double)field.get(obj); }else if(field.get(obj) instanceof Character){ objs[i][j] = (Character)field.get(obj); }else if(field.get(obj) instanceof Boolean){ objs[i][j] = (Boolean)field.get(obj); } } catch (SecurityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } return objs; } /** * 测试方法 * @param args * @throws FileNotFoundException * @throws IOException */ public static void main(String[] args) throws FileNotFoundException, IOException{ File file = new File("D:\\test\\quetoList.xlsx"); WriteExcelUtil ti = new WriteExcelUtil(); File desFile = new File("D:\\test\\mtest.xlsx"); if(desFile.exists()){ desFile.delete(); desFile.createNewFile(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("#contractName", "古镇唯美灯饰有限公司_HT20140826001"); map.put("$total", new BigDecimal(200000)); map.put("$equAndInsure", new BigDecimal(5000)); map.put("$engineerService", new BigDecimal(2000)); map.put("$maintainService", new BigDecimal(10000)); map.put("$oneFavourable", new BigDecimal(20000)); map.put("$contractedPrice", new BigDecimal(197000)); List<ProductPojo> list = new ArrayList<ProductPojo>(); ProductPojo pp = new ProductPojo(1,"HS-S21-D21-001","白炽灯","个",50,10.0,500.0,""); ProductPojo pp2 = new ProductPojo(2,"HS-S21-D21-002","台式灯","盏",100,100.0,10000.0,""); ProductPojo pp3 = new ProductPojo(3,"HS-S21-D21-003","路灯","盏",50,800.0,40000.0,""); ProductPojo pp4 = new ProductPojo(4,"HS-S21-D21-004","椰树灯","盏",100,2000.0,200000.0,""); ProductPojo pp5 = new ProductPojo(5,"HS-S21-D21-005","吊灯","盏",110,1000.0,110000.0,""); ProductPojo pp6 = new ProductPojo(6,"HS-S21-D21-006","白光灯","盏",100,20.0,2000.0,""); ProductPojo pp7 = new ProductPojo(7,"HS-S21-D21-007","日光灯","盏",80,50.0,4000.0,""); ProductPojo pp8 = new ProductPojo(8,"HS-S21-D21-008","节能灯","盏",60,60.0,3600.0,""); list.add(pp); list.add(pp2); list.add(pp3); list.add(pp4); list.add(pp5); list.add(pp6); list.add(pp7); list.add(pp8); Object[][] objs = ti.getObjectArr(list, list.size(), 8, ProductPojo.class); Workbook wb = ti.getInstance(file, desFile, map, objs , ProductPojo.class); FileOutputStream fos = new FileOutputStream(desFile); wb.write(fos); fos.flush(); fos.close(); } } |
|||
jfreechart demo | |||
jfreechart报表技术的原理简述: 1. 在web.xml中配置DisplayChart这个过滤器 2. 构造报表图形对象的数据集 3. 后台通过构造相应图形的数据集创建JFreeChart图形对象 4. 通过JFreeChart对象来生成相应的图片,这里需要用到jfreechart工具类ServletUtilities实现 5. 页面通过显示该图片从而实现报表的功能 说明: 1. DisplayChart过滤器主要是用来得到报表图片的地址。 2. 生成的报表图片的地址会被DisplayChart找到。 ---------------------------------- demo 1. 导入jar包 1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>chartDemo</display-name> <servlet> <servlet-name>chartServlet</servlet-name> <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class> </servlet> <servlet-mapping> <servlet-name>chartServlet</servlet-name> <url-pattern>/servlet/DisplayChart</url-pattern> </servlet-mapping> <servlet> <servlet-name>mychart</servlet-name> <servlet-class>com.chart.servlet.MyChartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mychart</servlet-name> <url-pattern>/mychart</url-pattern> </servlet-mapping> <servlet> <servlet-name>linechart</servlet-name> <servlet-class>com.chart.servlet.XYServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>linechart</servlet-name> <url-pattern>/linechart</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>XYServlet</display-name> <servlet-name>XYServlet</servlet-name> <servlet-class>com.chart.servlet.XYServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>XYServlet</servlet-name> <url-pattern>/XYServlet</url-pattern> </servlet-mapping> <servlet> <description>Bar chart Servlet</description> <display-name>BarChartServlet</display-name> <servlet-name>BarChartServlet</servlet-name> <servlet-class>com.chart.servlet.BarChartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BarChartServlet</servlet-name> <url-pattern>/BarChartServlet</url-pattern> </servlet-mapping> </web-app> 2.chartService.java package com.chart.service; import java.awt.Color; import java.awt.Font; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis3D; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.RendererUtilities; import org.jfree.chart.servlet.ServletUtilities; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; public class ChartService { /** * 构造报表图形对象需要的数据集--饼状图 */ public PieDataset createChartData(){ DefaultPieDataset pieDate = new DefaultPieDataset(); pieDate.setValue("C++", 20.0d); pieDate.setValue("C", 30.0d); pieDate.setValue("Java", 30.0d); pieDate.setValue("Object C", 15.0d); pieDate.setValue("others", 5.0d); return pieDate; } /** * 显示报表图片的数据集--柱形图数据集 */ public DefaultCategoryDataset barChartDataset(){ DefaultCategoryDataset dcd = new DefaultCategoryDataset(); // dcd.addValue(32, "Java", "2013-01"); // dcd.addValue(31, "C", "2013-01"); // dcd.addValue(20, "C++", "2013-01"); // dcd.addValue(15, "Object C", "2013-01"); // dcd.addValue(4, "others", "2013-01"); int rad = (int) (Math.random()*32 + 1); for(int i = 1; i < 6; i++){ rad = (int) (Math.random()*32 + 1); if(i == 1){ dcd.addValue(rad, "Java", "2013-01"); }else if(i == 2){ dcd.addValue(rad, "C", "2013-01"); }else if(i == 3){ dcd.addValue(rad, "C++", "2013-01"); }else if(i == 4){ dcd.addValue(rad, "Object C", "2013-01"); }else if(i == 5){ dcd.addValue(4, "others", "2013-01"); } } for(int i = 1; i < 6; i++){ rad = (int) (Math.random()*32 + 1); if(i == 1){ dcd.addValue(rad, "Java", "2013-02"); }else if(i == 2){ dcd.addValue(rad, "C", "2013-02"); }else if(i == 3){ dcd.addValue(rad, "C++", "2013-02"); }else if(i == 4){ dcd.addValue(rad, "Object C", "2013-02"); }else if(i == 5){ dcd.addValue(4, "others", "2013-01"); } } // dcd.addValue(32, "C", "2013-02"); // dcd.addValue(28, "Java", "2013-02"); // dcd.addValue(19, "Object C", "2013-02"); // dcd.addValue(18, "C++", "2013-02"); // dcd.addValue(5, "others", "2013-02"); return dcd; } /** * 创建JFreeChart对象 * @throws IOException */ public String createBarChart(HttpSession session) throws IOException{ JFreeChart chart = ChartFactory.createBarChart3D("Programing language top", "Month", "Programing use rate", barChartDataset(), PlotOrientation.VERTICAL, true, false, false); CategoryPlot plot = (CategoryPlot)chart.getPlot(); CategoryAxis3D axis = (CategoryAxis3D)plot.getDomainAxis(); axis.setAxisLineVisible(true); axis.setLabelFont(new Font(Font.DIALOG_INPUT, Font.ITALIC, 14)); String filename = ServletUtilities.saveChartAsJPEG(chart, 800, 400, session); return filename; } /** * 设置 * @throws IOException */ public String createXYChart(HttpSession session) throws IOException{ JFreeChart freechart = ChartFactory.createTimeSeriesChart("zhe xian tu", "month", "rate", createXYDataset(), true, true, false); freechart.setTitle("Programing language use line picture"); XYPlot plot = (XYPlot)freechart.getPlot(); plot.setDomainZeroBaselineVisible(true); DateAxis date = (DateAxis)plot.getDomainAxis(); date.setDateFormatOverride(new SimpleDateFormat("MM")); freechart.getLegend().setItemFont(new Font(Font.DIALOG,Font.BOLD,14)); String filename = ServletUtilities.saveChartAsJPEG(freechart, 1600, 425, session); return filename; } /** * 创建一个用来显示需要的数据集--折线图数据集 */ public XYDataset createXYDataset(){ TimeSeries ts = new TimeSeries("Java", Month.class); ts.add(new Month(1,2013), 120.0); ts.add(new Month(2,2013), 125.0); ts.add(new Month(3,2013), 110.0); ts.add(new Month(4,2013), 130.0); ts.add(new Month(5,2013), 135.0); ts.add(new Month(6,2013), 124.0); ts.setDescription("Java use rate picture"); TimeSeries ts2 = new TimeSeries("C", Month.class); ts2.add(new Month(1,2013), 125.0); ts2.add(new Month(2,2013), 135.0); ts2.add(new Month(3,2013), 115.0); ts2.add(new Month(4,2013), 110.0); ts2.add(new Month(5,2013), 125.0); ts2.add(new Month(6,2013), 134.0); ts2.setDescription("C use rate picture"); TimeSeries ts3 = new TimeSeries("C++", Month.class); ts3.add(new Month(1,2013), 103.0); ts3.add(new Month(2,2013), 105.0); ts3.add(new Month(3,2013), 100.0); ts3.add(new Month(4,2013), 81.0); ts3.add(new Month(5,2013), 101.0); ts3.add(new Month(6,2013), 92.0); ts3.setDescription("C++ use rate picture"); TimeSeries ts4 = new TimeSeries("Object C", Month.class); ts4.add(new Month(1,2013), 110.0); ts4.add(new Month(2,2013), 105.0); ts4.add(new Month(3,2013), 102.0); ts4.add(new Month(4,2013), 90.0); ts4.add(new Month(5,2013), 105.0); ts4.add(new Month(6,2013), 95.0); ts4.setDescription("Object C use rate picture"); TimeSeries ts5 = new TimeSeries("Others", Month.class); ts5.add(new Month(1,2013), 50.0); ts5.add(new Month(2,2013), 65.0); ts5.add(new Month(3,2013), 52.0); ts5.add(new Month(4,2013), 56.0); ts5.add(new Month(5,2013), 66.0); ts5.add(new Month(6,2013), 55.0); ts5.setDescription("Others use rate picture"); TimeSeriesCollection tsc = new TimeSeriesCollection(); tsc.addSeries(ts); tsc.addSeries(ts2); tsc.addSeries(ts3); tsc.addSeries(ts4); tsc.addSeries(ts5); return tsc; } /** * 创建报表图形对象(即JFreeChart类的对象) */ public JFreeChart getJFreeChartInstance(){ JFreeChart jfreechart = ChartFactory.createPieChart3D("programing language use's rate", createChartData(),true,false,true); PiePlot plot = (PiePlot) jfreechart.getPlot(); plot.setLabelFont(new Font(Font.SANS_SERIF, Font.BOLD, 12)); plot.setCircular(true); plot.setLabelGap(0.02d); int rav =(int) (Math.random() * 4 + 1); System.out.println(rav); Map<Integer , Color> map = new HashMap<Integer, Color>(); map.put(new Integer(1), Color.white); map.put(new Integer(2), Color.pink); map.put(new Integer(3), Color.lightGray); map.put(new Integer(4), Color.cyan); plot.setBackgroundPaint(map.get(rav)); plot.setInteriorGap(0.04); plot.setOutlineVisible(true); // plot.setBackgroundAlpha(0.006f); plot.setForegroundAlpha(0.8f); //plot.setAutoPopulateSectionOutlineStroke(false); plot.setBaseSectionOutlinePaint(new Color(255,100,100)); return jfreechart; } /** * 通过ServletUtilities来生成图片 * @throws IOException */ public String getImageName(HttpSession session) throws IOException{ String filename = ServletUtilities.saveChartAsJPEG(getJFreeChartInstance(), 400, 400, session); return filename; } } 3.BarChartServlet.java package com.chart.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chart.service.ChartService; /** * Servlet implementation class BarChartServlet */ public class BarChartServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public BarChartServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChartService cs = new ChartService(); String filename = cs.createBarChart(request.getSession()); request.setAttribute("filename", filename); request.getRequestDispatcher("/showChartImg.jsp").forward(request, response); } } 4. MyChartServlet.java package com.chart.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chart.service.ChartService; @SuppressWarnings("serial") public class MyChartServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChartService cs = new ChartService(); String filename = cs.getImageName(request.getSession()); request.setAttribute("filename", filename); response.setCharacterEncoding("UTF-8"); request.getRequestDispatcher("showChartImg.jsp").forward(request, response); } @Override public void destroy() { // TODO Auto-generated method stub super.destroy(); } @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); } } 5. XYServlet.java package com.chart.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chart.service.ChartService; /** * Servlet implementation class XYServlet */ public class XYServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public XYServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChartService scs = new ChartService(); String filename = scs.createXYChart(request.getSession()); request.setAttribute("filename", filename); request.getRequestDispatcher("/showChartImg.jsp").forward(request, response); } } 6. index.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="mychart">查看饼状图</a><br /> <a href="linechart">查看折线图</a><br /> <a href="BarChartServlet">查看柱状图</a> </body> </html> 7.showChartImg.jsp <%@ 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> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>饼状图</title> <script type="text/javascript"> setInterval("window.location.reload();",1000*5); </script> </head> <body> <img alt="编程语言使用率饼状图" src="servlet/DisplayChart?filename=<%=request.getAttribute("filename")%>"> </body> </html> |