`
jxqc_job
  • 浏览: 529 次
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
枚举用法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();
            }
        }
		
		
		
	
		
		
		
获取Birt报表引擎对象 获取birt报表引擎对象
import javax.servlet.ServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
/**在java web中创建报表引擎对象的工厂*/
public class BirtEngineFactory {
	private static IReportEngine birtEngine = null;

	public static synchronized IReportEngine getBirtEngine( ServletContext sc ) {
		if (birtEngine == null) {
			EngineConfig config = new EngineConfig();
			config.setBIRTHome("");
			IPlatformContext context = new PlatformServletContext( sc );
			config.setPlatformContext( context );
			try{
				Platform.startup( config );
				IReportEngineFactory factory = ( IReportEngineFactory )
				Platform.createFactoryObject( 
				IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
				birtEngine = factory.createReportEngine( config );
			}catch ( Exception e ) { 
				e.printStackTrace( ); 
			}
		}
		return birtEngine;
	}
}
birtDemo.rptdesign文件02 birtdemo.rptdesign文件02
<structure name="cachedMetaData">
                <list-property name="resultSet">
                    <structure>
                        <property name="position">1</property>
                        <property name="name">recv_lead</property>
                        <property name="dataType">string</property>
                    </structure>
                    <structure>
                        <property name="position">2</property>
                        <property name="name">recv_time</property>
                        <property name="dataType">date-time</property>
                    </structure>
                    <structure>
                        <property name="position">3</property>
                        <property name="name">give_time</property>
                        <property name="dataType">date-time</property>
                    </structure>
                    <structure>
                        <property name="position">4</property>
                        <property name="name">class_no</property>
                        <property name="dataType">string</property>
                    </structure>
                    <structure>
                        <property name="position">5</property>
                        <property name="name">od_state</property>
                        <property name="dataType">string</property>
                    </structure>
                    <structure>
                        <property name="position">6</property>
                        <property name="name">notesCount</property>
                        <property name="dataType">integer</property>
                    </structure>
                </list-property>
            </structure>
            <property name="dataSource">defectScriptDatasource</property>
            <method name="open"><![CDATA[count = 0;
defectListBean = listBean;]]></method>
            <method name="fetch"><![CDATA[if(count < defectListBean.size()){
    row["recv_lead"] = defectListBean.get(count).getRecv_lead();
    row["recv_time"] = defectListBean.get(count).getRecv_time();
    row["give_time"] = defectListBean.get(count).getGive_time();
    row["class_no"] = defectListBean.get(count).getClass_no();
    if("2".equals(defectListBean.get(count).getOd_state())){
        row["od_state"] = "已完成";
    }
    row["notesCount"] = defectListBean.get(count).getNotesCount();
    if(null == defectListBean.get(count).getNotesCount()){
        row["notesCount"] = 0;
    }
    row["totalCount"] = defectListBean.get(count).getTotalCount();
    if(null == defectListBean.get(count).getTotalCount()){
        row["totalCount"] = 0;
    }
    row["undoneCount"] = defectListBean.get(count).getUndoneCount();
    if(null == defectListBean.get(count).getUndoneCount()){
        row["undoneCount"] = 0;
    }
    row["doneCount"] = defectListBean.get(count).getDoneCount();
    if(null == defectListBean.get(count).getDoneCount()){
        row["doneCount"] = 0;
    }
    row["doneRate"] = defectListBean.get(count).getDoneRate();
    if(null == defectListBean.get(count).getDoneRate()){
        row["doneRate"] = 100;
    }
    row["avgTime"] = defectListBean.get(count).getAvgTime();
    if(null == defectListBean.get(count).getAvgTime()){
        row["avgTime"] = 0;
    }
    row["remainDoneCount"] = defectListBean.get(count).getRemainDoneCount();
    if(null == defectListBean.get(count).getRemainDoneCount()){
        row["remainDoneCount"] = 0;
    }
    count++;
    return true;
}
return false;]]></method>
        </script-data-set>
    </data-sets>
birtDemo.rptdesign文件01 birtdemo.rptdesign文件01
<?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="defectScriptDatasource" id="8"/>
    </data-sources>
    <data-sets>
        <script-data-set name="defectScriptDataCollection" id="9">
            <list-property name="resultSetHints">
                <structure>
                    <property name="position">1</property>
                    <property name="name">recv_lead</property>
                    <property name="dataType">string</property>
                </structure>
                <structure>
                    <property name="position">2</property>
                    <property name="name">recv_time</property>
                    <property name="dataType">date-time</property>
                </structure>
                <structure>
                    <property name="position">3</property>
                    <property name="name">give_time</property>
                    <property name="dataType">date-time</property>
                </structure>
                <structure>
                    <property name="position">4</property>
                    <property name="name">class_no</property>
                    <property name="dataType">string</property>
                </structure>
                <structure>
                    <property name="position">5</property>
                    <property name="name">od_state</property>
                    <property name="dataType">string</property>
                </structure>
                <structure>
                    <property name="position">6</property>
                    <property name="name">notesCount</property>
                    <property name="dataType">integer</property>
                </structure>
            </list-property>
            <list-property name="columnHints">
                <structure>
                    <property name="columnName">recv_lead</property>
                </structure>
                <structure>
                    <property name="columnName">recv_time</property>
                </structure>
                <structure>
                    <property name="columnName">give_time</property>
                </structure>
                <structure>
                    <property name="columnName">class_no</property>
                </structure>
                <structure>
                    <property name="columnName">od_state</property>
                </structure>
                <structure>
                    <property name="columnName">notesCount</property>
                </structure>
            </list-property>
自己实现的简单的请假流程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>
SVN服务器的配置 svn服务器的配置
1.下载Subversion安装包

2.配置SVN版本库


3.在Windows中配置SVN服务
  --在windows中添加SVN服务
其中D:\Program Files\Subversion\为Subversion安装路径,C:\SVN-Project为版本库路径
在cmd命令下输入如下命令:

sc create svn binpath= "D:\Program Files\Subversion\bin\svnserve.exe --service -r C:\SVN-Project" DisplayName= "Subversion Server" depend= Tcpip start= auto



详细配置参照百度文库中的“SVN配置基础教程 MyEclipse7.5”即可。


uploadify传参解决方法 uploadify传参解决方法
1.upload2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	pageContext.setAttribute("purpose", "Temp Offet");
	String p = "Temp Fianl123";
	String e = "Orange123";
	String u = p+e;
%>
<!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>
		<base href="<%=basePath%>">
		<link href="<%=basePath%>uploadify2/uploadify.css" rel="stylesheet" type="text/css">
		<script type="text/javascript" src="<%=basePath%>uploadify2/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="<%=basePath%>uploadify2/swfobject.js"></script>
		<script type="text/javascript" src="<%=basePath%>uploadify2/jquery.uploadify.v2.1.4.min.js"></script>
	</head>
<body>
<div id="fileQueue"></div>
	<input type="file" name="uploadify" id="uploadify" />
    <p>
        <a href="javascript: jQuery('#uploadify').uploadifyUpload()">开始上传</a> 
		<a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a>
	</p>
</body>
<script type="text/javascript">
	//官方网址:http://www.uploadify.com/
	$(document).ready(function(){
		//$("#uploadify").uploadifySettings('scriptData',	{'name':'liudong','age':22});
		$("#uploadify").uploadify({
			'uploader'	:	"<%=basePath%>uploadify2/uploadify.swf",
			'script'    :	"<%=basePath%>/servlet/UploadPhotoServlet?act=upload123<%=u%>@",
			'cancelImg' :	"<%=basePath%>uploadify2/cancel.png",
			'folder'	:	"uploads",//上传文件存放的路径,请保持与uploadFile.jsp中PATH的值相同
			'queueId'	:	"fileQueue",
			'queueSizeLimit'	:	10,//限制上传文件的数量
			'fileExt'	:	"*.rar,*.zip,*.png,*.txt",
			//'fileDesc'	:	"RAR *.rar",//限制文件类型
			'auto'		:	false,
			'multi'		:	true,//是否允许多文件上传
			'simUploadLimit':	2,//同时运行上传的进程数量
			'buttonText':	"files",
			//'scriptData':	{'act':'liudong','purpose':'External'},//这个参数用于传递用户自己的参数,此时'method' 必须设置为GET, 后台可以用request.getParameter('name')获取名字的值
			'method'	:	"GET",
			'onUploadSuccess':function(file,data,response){
				alert(file.name);
			}
		});
		
		//$("#uploadify").uploadifySettings();
	});
</script>
</html>


2. UploadPhotoServlet.java

package com.org.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@SuppressWarnings("serial")
public class UploadPhotoServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UploadPhotoServlet() {
		super();
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String param = req.getParameter("act");
		String[] act = param.split("@");
//		System.out.println(act[0]);
		System.out.println("act-->"+act[0].split("123")[0]);
		if(!"upload".equals(act[0].split("123")[0])){
			return ;
		}
		System.out.println("purpose-->"+act[0].split("123")[1]);
		System.out.println("purpose-->"+act[0].split("123")[2]);
		String savePath = this.getServletConfig().getServletContext().getRealPath("");
		System.out.println("-----"+savePath);
		savePath = savePath+"/uploads/";
		File f1 = new File(savePath);
		if(!f1.exists()){
			f1.mkdirs();
		}
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(req);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		if(fileList==null){
			resp.getWriter().print("No file upload!");
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String extName = "";
		while(it.hasNext()){
			FileItem item = it.next();
			if(!item.isFormField()){//isFormField介绍:true=表单输入 域,false=文件上传域。
				name = item.getName();
				//long size = item.getSize();
				//String type = item.getContentType();
				if(name == null || name.trim().equals("")){
					continue;
				}
				//扩展名格式
				if(name.lastIndexOf(".")>=0){
					extName = name.substring(name.lastIndexOf("."));
				}
				File file = null;
				do{
					//生成文件名
					name = UUID.randomUUID().toString();
					file = new File(savePath+name+extName);
				}while(file.exists());
				File saveFile = new File(savePath+name+extName);
				try {
					item.write(saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		resp.getWriter().print(name+extName);
		
	}

}
多线程Demo--生产者与消费者 多线程demo--生产者与消费者
java多线程编程:果农摘水果,人们吃水果(生产者与消费者)
1. Fruit.java
package com.thread.test;

import java.util.Random;

public class Fruit {
	int id; //水果编号
	int number; //水果编号计数器
	String variety; //水果品种
	String[] varietys = "苹果,桃子,梨子,香蕉,西瓜,荔枝,葡萄".split(","); //水果品种数组
	public Fruit(){
		this.variety = this.varietys[new Random().nextInt(7)];
		this.id = ++this.number;
	}
}

2. FruitBasket.java
package com.thread.test.copy;

public class FruitBasket {
	Fruit[] fruits = new Fruit[10]; // 水果筐的容量
	int x; // 下一个水果放置的位置
	int num; // 水果编号

	public FruitBasket() {
		x = 0;
		num = 0;
		System.out.println("水果筐的容量为:" + fruits.length);
	}

	public boolean isEmpty() {
		return x == 0 ? true : false;
	}

	public boolean isFull() {
		return x == fruits.length ? true : false;
	}

	/**
	 * 放水果
	 * 
	 * @throws InterruptedException
	 */
	public synchronized void putFruit(String name) {
		if (isFull()) {
			try {
				this.wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			return;
		}
		fruits[x] = new Fruit(); // 放一个水果
		System.out
				.println(name + "放了一个" + fruits[x].variety + ":编号为" + (++num)); // 输出这个苹果信息
		fruits[x].id = num; // 给这个水果设置个编号
		x = x + 1;
//		System.out.println("----------框中剩余的水果数为:" + x);
		display();
		this.notify();
	}

	private void display() {
		for(int i = 0; i < fruits.length; i++){
			Fruit fruit = fruits[i];
			if(fruit != null){
				System.out.print("No." + fruits[i].id + ":" + fruits[i].variety + "\t\t");
			}else{
				System.out.print("【" + (i + 1 ) + "】" + "\t\t");
			}
		}
		System.out.println();
	}

	/**
	 * 吃水果
	 * 
	 * @throws InterruptedException
	 */
	public synchronized void popFruit(String name) {
		if (isEmpty()) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return;
		}
		// 水果筐中最上面的一个水果的位置
		x--;
		// 输出小孩吃的该水果的信息
		System.out.println(name + "把编号为:No." + fruits[x].id + "的" + fruits[x].variety + "给吃了");
		// 小孩拿出水果筐中最上面的一个水果吃
		fruits[x] = null;
		// 水果筐中剩余的水果数量
//		System.out.println("**********框中剩余的水果数为:" + x);
		display();
		this.notify();
	}

}



3. Farmer.java
package com.thread.test;

import java.util.Random;

public class Farmer implements Runnable{
	private FruitBasket fb; //水果
	private String name; //果农的姓名
	
	public Farmer(String name, FruitBasket fb){
		this.name = name;
		this.fb = fb;
	}
	@Override
	public void run(){
		
		while(true){
			fb.putFruit(name);
			int t = new Random().nextInt(5000);
//			System.out.println(name+":"+Thread.currentThread().getName() + "休眠" + t
//					+ "毫秒");
			try {
				Thread.sleep(t);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}


4. XiaoHai.java
package com.thread.test;

import java.util.Random;

public class XiaoHai implements Runnable{
	private FruitBasket fb; //水果
	private String name; //小孩的姓名
	public XiaoHai(String name, FruitBasket fb){
		this.fb = fb;
		this.name = name;
	}
	@Override
	public void run() {
		while(true){
			fb.popFruit(name);
			int t = new Random().nextInt(5000);
//			System.out.println(name+":"+Thread.currentThread().getName() + "休眠" + t
//					+ "毫秒");
			try {
				Thread.sleep(t);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}


5. TestDemo.java
package com.thread.test;

public class TestDemo {
	public static void main(String[] args) {
		FruitBasket fb = new FruitBasket();
		Farmer f = new Farmer("张三",fb);
		Farmer f2 = new Farmer("李四",fb);
		Farmer f3 = new Farmer("王五",fb);
		
		Thread tf = new Thread(f);
		Thread tf2 = new Thread(f2);
		Thread tf3 = new Thread(f3);
		
		XiaoHai xh = new XiaoHai("悟空", fb);
		XiaoHai xh2 = new XiaoHai("八戒", fb);
		XiaoHai xh3 = new XiaoHai("唐僧", fb);
		
		Thread txh = new Thread(xh);
		Thread txh2 = new Thread(xh2);
		Thread txh3 = new Thread(xh3);
				
		tf.start();
		tf2.start();
		tf3.start();
		
		txh.start();
		txh2.start();
		txh3.start();
		
	}
}
 
修复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>
jfreechart报表技术的原理简述: jfreechart报表技术的原理简述:
jfreechart报表技术的原理简述:
1. 在web.xml中配置DisplayChart这个过滤器
2. 构造报表图形对象的数据集
3. 后台通过构造相应图形的数据集创建JFreeChart图形对象
4. 通过JFreeChart对象来生成相应的图片,这里需要用到jfreechart工具类ServletUtilities实现
5. 页面通过显示该图片从而实现报表的功能



说明:
1. DisplayChart过滤器主要是用来得到报表图片的地址。
2. 生成的报表图片的地址会被DisplayChart找到。
Java调用mysql存储过程的简单示例 java调用mysql存储过程的简单示例
Java调用mysql存储过程的简单示例:
1.类文件
package com.db.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
 * java调用mysql存储过程的示例
 */
public class DBUtil2 {
	public Connection getConnection() {
		String driverName = "com.mysql.jdbc.Driver";
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Connection conn = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost/db_pro?useUnicode=true&characterEncoding=GBK","root","");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public boolean addUser(String username,String userpass){
		Connection conn = getConnection();
		 String sql = "{call pro_add_user(?,?)}";
		if(null != conn){
			try {
				CallableStatement cs = conn.prepareCall(sql);
				cs.setString(1, username);
				cs.setString(2, userpass);
				int r = cs.executeUpdate();
				if(r > 0){
					return true;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	public void selectAll(){
		Connection conn = getConnection();
		 String sql = "{call pro_select_all_user()}";
		if(null != conn){
			try {
				CallableStatement cs = conn.prepareCall(sql);
				cs.execute();
				ResultSet rs = cs.getResultSet();
				ResultSetMetaData rsmd = rs.getMetaData();
				while(rs.next()){
					int id = rs.getInt(1);
					String name = rs.getString(2);
					String pass = rs.getString(3);
					System.out.println(rsmd.getColumnName(1)+"="+id+", "+rsmd.getColumnName(2)+"="+name+", "+rsmd.getColumnName(3)+"="+pass);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		new DBUtil2().selectAll();
	}
}


2.数据库部分
# Host: 127.0.0.1  (Version: 5.5.11)
# Date: 2014-07-29 16:05:07
# Generator: MySQL-Front 5.3  (Build 1.21)
drop database if exists db_pro;
create database db_pro;
USE `db_pro`;

#
# Source for table "tb_user"
#

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `userpass` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=gbk;

#
# Data for table "tb_user"
#

INSERT INTO `tb_user` VALUES (1,'zhangsan','123'),(2,'wangwu','abc'),(3,'李四','efg');



use db_pro;
create PROCEDURE pro_add_user(in name varchar(50),in pass varchar(50))
begin 
      INSERT into tb_user(username,userpass) values(name,pass);
end; 

create procedure pro_select_all_user()
begin
     select * from tb_user;
end;

select * from tb_user;
自己的文件批量压缩demo 自己的文件批量压缩demo
package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 文件压缩--demo
 */
public class ZipUtil {
	public static void main(String[] args) throws Exception{
		String path = "D:\\test";
		File file = new File(path);
		File[] files = file.listFiles();
		List<File> fl = new ArrayList<File>();
		//文件过滤--只保留.txt文件即可
		for(File f : files){
			if(f.getName().endsWith(".txt")){
				fl.add(f);
			}
		}
		ZipEntry ze = null;
		//第一步:创建一个ZipOutputStream对象,参数为生成的目标文件
		ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(new File("d:\\test","z_test.zip")));
		//第二步:遍历需要压缩的文件集合
		for(File fe : fl){
			//第三步:创建一个ZipEntry对象,参数为遍历文件的文件名
			ze = new ZipEntry(fe.getName());
			//第四步:将ZipEntry对象放入ZipOutputStream对象中
			zo.putNextEntry(ze);
			//第五步:创建遍历文件的输入流(即使用待压缩的文件创建文件输入流)
			FileInputStream fis = new FileInputStream(fe);
			byte[] b = new byte[1024];
			int context = -1;
			//第六步:循环读取第五步创建的文件输入流,并将从文件输入流中读取的内容写入ZipOutputStream对象中
			while((context = fis.read(b, 0, 1024)) != -1){
				zo.write(b, 0, context);
			}
			zo.flush();
			fis.close();
		}
		zo.close();
		
	}
}
我的工作流demo-7_sql语句
insert into tb_process_picture(nodeName, nodeLocation_x, nodeLocation_y, nodeLocation_w, nodeLocation_h) 
values('开始',74,156,48,48);
insert into tb_process_picture(nodeName, nodeLocation_x, nodeLocation_y, nodeLocation_w, nodeLocation_h) 
values('主管审批',197,158,92,52);
insert into tb_process_picture(nodeName, nodeLocation_x, nodeLocation_y, nodeLocation_w, nodeLocation_h) 
values('经理审批',517,157,92,52);
insert into tb_process_picture(nodeName, nodeLocation_x, nodeLocation_y, nodeLocation_w, nodeLocation_h) 
values('老板审批',522,289,92,52);
insert into tb_process_picture(nodeName, nodeLocation_x, nodeLocation_y, nodeLocation_w, nodeLocation_h) 
values('结束',747,157,48,48);
commit;
我的工作流demo-6
30.qingjia.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=UTF-8">
<title>请假</title>
</head>
<body>
	<form action="user/deployFlow!apply" method="post">
		<table>
			<tr>
				<th colspan="2">请假申请</th>
			</tr>
			<tr>
				<td>请假人:</td>
				<td><input type="text" name="askForLeave.aflName" /></td>
			</tr>
			<tr>
				<td>请假天数:</td>
				<td><input type="text" name="askForLeave.aflDays" /></td>
			</tr>
			<tr>
				<td>请假事由:</td>
				<td><input type="text" name="askForLeave.aflDesc" /></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

31.queryDeployment.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>查看已部署的流程</title>
</head>
<body>
	<table width="30%">
	<c:forEach var="deployProcess" items="${deployProcesses}">
		<tr>
			<td>${deployProcess.id}</td>
			<td>${deployProcess.name}</td>
			<td>${deployProcess.version}</td>
			<td><a href="">流程删除</a></td>
			<td><a href="deployFlow!showPictureNode?id=${deployProcess.id}">查看流程图</a></td>
		</tr>
	</c:forEach> 
	</table>
</body>
</html>

32.success.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=UTF-8">
<title>success</title>
</head>
<body>
	success!!!
</body>
</html>

33.view.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>show</title>
<%
	String id = request.getParameter("id");
%>
</head>
<body>
<img src="user/deployFlow!showImg?id=<%=id%>" style="position:absolute;left:0px;top:0px;">
<div style="position:absolute;border:1px solid red;left:<s:property value="#request.X"/>px;top:<s:property value="#request.Y"/>px;width:<s:property value="#request.width"/>px;height:<s:property value="#request.height"/>px;"></div>
</body>
</html>

34.waitingTask.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>待办任务</title>
</head>
<body>
	<table border="1" width="40%">
		<tr>
			<th>id</th>
			<th>请假人</th>
			<th>请假天数</th>
			<th>状态</th>
			<th>操作</th>
		</tr>
		<c:forEach var="askForLeave" items="${taskList}">
			<tr>
				<td><a href="deployFlow!query?act=${askForLeave.currentNodeNum}&id=${askForLeave.id}">${askForLeave.id}</a></td>
				<td>${askForLeave.aflName}</td>
				<td>${askForLeave.aflDays}</td>
				<td>${askForLeave.auditStatus}</td>
				<td><a href="deployFlow!showPictureNode?id=${askForLeave.currentNodeNum}">查看流程图</a></td>
			</tr>
		</c:forEach> 
	</table>
</body>
</html>
我的工作流demo-5
22.log4j.properties
#log4j.rootCategory=INFO,stdout,file  
#配置根Logger  
log4j.rootLogger=INFO,file,CONSOLE   
log4j.additivity.org.apache=true  
  
#日志信息输出到控制台 
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender   
log4j.appender.CONSOLE.Threshold=INFO   
log4j.appender.CONSOLE.Target=System.out   
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout   
log4j.appender.CONSOLE.layout.ConversionPattern=%d %l-%m%n 

#输出到指定的日志文件
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender  
#日志文件的输出路径  
log4j.appender.file.File=d\:/hplog/mylogs.log    
log4j.appender.FILE.MaxFileSize=10MB 
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#输出INFO级别以上的日志  
log4j.appender.file.Threshold = INFO   
log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %l-%m%n   

23.proxool.xml
<?xml version="1.0" encoding="UTF-8"?>
<something-else-entirely>
	<proxool>
		<!--连接池的别名 -->
		<alias>hp</alias>
		<!--proxool只能管理由自己产生的连接 -->
		<driver-url>jdbc:mysql://10.23.28.231:3306/db_ssh2jbpm</driver-url>
        <!-- JDBC驱动程序-->
		<driver-class>com.mysql.jdbc.Driver</driver-class>
		<driver-properties>
			<property name="user" value="root" />
			<property name="password" value="Td123456" />
		</driver-properties>
		
		<!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回 收,超时的销毁 -->
		<house-keeping-sleep-time>90000</house-keeping-sleep-time>
		<!-- 指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的 用户连接就不会被接受 -->
		<simultaneous-build-throttle>20</simultaneous-build-throttle>
		<!-- 最少保持的空闲连接数 -->
		<prototype-count>5</prototype-count>
		<!-- 允许最大连接数,超过了这个连接,再有请求时,就排在队列中等候,最大的 等待请求数由maximum-new-connections决定 -->
		<maximum-connection-count>100</maximum-connection-count>
		<!-- 最小连接数 -->
		<minimum-connection-count>10</minimum-connection-count>
		<!-- add time: 2013-5-14 begin -->
		<test-before-use>true</test-before-use>
		<test-after-use>true</test-after-use>
		<house-keeping-test-sql>SELECT CURRENT_USER</house-keeping-test-sql>
		<!-- add time: 2013-5-14 end -->
	</proxool>
</something-else-entirely>

24.struts.properties
struts.multipart.maxSize=314572800

25.struts.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <!-- 将struts2的Action交给Spring管理 -->
    <constant name="struts.objectFactory" value="spring" />
	<!-- 配置其他常量 -->
	<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	
	<!-- 用户模块的Action配置 -->
	<package name="struts_user" extends="struts-default" namespace="/user">
		<action name="user" class="userAction">
			<result name="success" type="redirect">/index.jsp</result>
			<!-- <result name="input">/login.jsp</result> -->
		</action>
		<action name="deployFlow" class="deployFlowAction">
			<result name="success">/queryDeployment.jsp</result>
			<result name="queryDeployment">/queryDeployment.jsp</result>
			<result name="showPic">/view.jsp</result>
			<result name="waitingTask">/waitingTask.jsp</result>
			<result name="audit">/audit.jsp</result>
		</action>
		<action name="req" class="deployFlowAction" method="taskStart"></action>
	</package>
	
</struts>

26.addUser.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=UTF-8">
<title>添加用户</title>
</head>
<body>
	<h3>添加用户</h3>
	<form action="user/user!addUser" method="post">
		姓名: <input type="text" id="name" name="user.name"/><br /><br />
		年龄: <input type="text" id="age" name="user.age"/><br /><br />
		<input type="submit" value="添加"/>
	</form>
</body>
</html>

27.audit.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=UTF-8">
<title>审批</title>
</head>
<body>
	<form action="user/deployFlow!audit" method="post">
		<table>
			<tr>
				<th colspan="2">${title}</th>
			</tr>
			<tr>
				<td>请假人:</td>
				<td>${askForLeave.aflName}</td>
			</tr>
			<tr>
				<td>请假天数:</td>
				<td>${askForLeave.aflDays}</td>
			</tr>
			<tr>
				<td>审批结果:</td>
				<td>
					<select name="auditResult">
						<option value="true">批准</option>
						<option value="false">不批准</option>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="提交" /></td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="hidden" name="askForLeave.id" value="${askForLeave.id}" />
					<input type="hidden" name="askForLeave.aflDays" value="${askForLeave.aflDays}" />
					<input type="hidden" name="askForLeave.currentNodeNum" value="${askForLeave.currentNodeNum}" />
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

28.error.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=UTF-8">
<title>error</title>
</head>
<body>
	error!!!
</body>
</html>

29.index.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=UTF-8">
<title>welcome</title>
<style type="text/css">
	#top{
		width:99%;
		height:50px;
		float:top;
		border-color:blue;
		border:1px solid;
	}
	#main{
		width:100%;
		height:84%;
		float:top;
		position:absolute;
	}
	#leftFrame{
		width:10%;
		height:100%;
		border:1px solid;
		float:left;
	}
	#rightFrame{
		width:88%;
		height:100%;
		border:1px solid;
		float:left;
	} 
	#treeDiv{
		margin-left:10%;
		background-color:white;
	}
	div{
		font-size:14px;
	}
	#bg_frame{
		background-color:lightblue;
	}
</style>
</head>
<body>
	<div id="top">事务管理系统</div>
	<div id="main">
		<div id="leftFrame">
			<div>
				<div id="bg_frame">日常审批</div>
				<div id="treeDiv"><a href="user/deployFlow!waitingTask">待办任务</a></div>
				<div id="treeDiv"><a href="user/deployFlow!historyTask">已办任务</a></div>
			</div>
			<div>
				<div id="bg_frame">日常任务</div>
				<div id="treeDiv"><a href="qingjia.jsp">请假</a></div>
			</div>
		</div>
		<div id="rightFrame">
			
		</div> 
	</div>
</body>
</html>
我的工作流demo-4
15.qj.jpdl.xml
<?xml version="1.0" encoding="UTF-8"?>

<process name="qj" id="qj" xmlns="http://jbpm.org/4.4/jpdl">
   <start name="start1" g="74,156,48,48">
      <transition name="to 主管审批" to="主管审批" g="-35,-26"/>
   </start>
   <end name="end1" g="747,157,48,48"/>
   <decision name="exclusive1" g="395,160,48,48">
      <transition name="to 经理审批" to="经理审批" g="-32,-28">
      	<condition expr="#{tra='to_manager'}"></condition>
      </transition>
      <transition name="to 老板审批" to="老板审批" g="422,316:-69,-22">
      	<condition expr="#{tra='to_boss'}"></condition>
      </transition>
      <transition name="to end1" to="end1" g="419,59:-56,22"/>
   </decision>
   <task name="主管审批" g="197,158,92,52">
      <transition name="to exclusive1" to="exclusive1" g="-33,-25"/>
   </task>
   <task name="经理审批" g="517,157,92,52">
      <transition name="to end1" to="end1" g="-50,-22"/>
   </task>
   <task name="老板审批" g="522,289,92,52">
      <transition name="to end1" to="end1" g="-50,-22"/>
   </task>
</process>

16.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.dan.action.UserAction">
		<property name="userService" ref="userService"></property>
	</bean>
</beans>

17.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">
	<!-- 配置HibernateTemplate bean -->
	<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean> -->
	<!-- 配置Dao层bean -->
	<!-- <bean id="dQDocumentDaoImpl" class="com.tdtech.pdm.create.dao.impl.DQDocumentDaoImpl">
		<property name="hibernateTemplate" ref="hibernateTemplate"></property>
	</bean> -->
	<bean id="userDao" class="com.dan.dao.impl.UserDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>

18.applicationContext_db.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">
	<!-- 配置sesionFactory-->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
	</bean> 
	<!-- 配置事物管理器bean -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<aop:config>
		<aop:pointcut id="entryPointMethod" expression="execution(* com.dan.service.impl.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="entryPointMethod"/>
	</aop:config>
	<aop:config>
		<aop:pointcut id="jobspacePointMethod" expression="execution(* com.dan.service.impl.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="jobspacePointMethod"/>
	</aop:config>
	<!-- 配置事物 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="create*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="add*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="delete*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="update*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="apply*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="save*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
		</tx:attributes>
	</tx:advice>
</beans>

19.applicationContext_service.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">
	<!--配置service层bean -->
	<bean id="userService" class="com.dan.service.impl.UserService">
		<property name="userDao" ref="userDao"></property>
	</bean>
	
</beans>

20.ehcache.xml
<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
    <cache name="com.happiness.pojo.APojo"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />
</ehcache>

21.hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 加载proxool数据库连接池 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
		<property name="hibernate.proxool.pool_alias">hp</property>
		<property name="hibernate.proxool.xml">proxool.xml</property>
		<!-- 自动生成数据表文件 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!--指定数据库语言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 显示sql语句 -->
		<property name="show_sql">true</property>
		
		<!-- 加载二级缓存 -->
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		
		<!-- 加载hibernate映射文件 -->
		<!-- <mapping resource="com/tdtech/pdm/create/pojo/DQDocumentPojo.hbm.xml" /> -->
		<mapping resource="com/dan/entity/User.hbm.xml" />
		<mapping resource="com/dan/entity/AskForLeave.hbm.xml" />
		<mapping resource="com/dan/entity/ProcessPicture.hbm.xml" />
	</session-factory>
</hibernate-configuration>
我的工作流demo-3
12.CharsetEncodingFilter.java
package com.dan.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharsetEncodingFilter implements Filter{
	/**
	 * 销毁方法
	 */
	public void destroy() {
		
	}
	/**
	 * 字符乱码处理方法
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response=(HttpServletResponse)res;
		HttpServletRequest request=(HttpServletRequest)req;
		String name=request.getMethod();  //name为请求方式
		if("post".equalsIgnoreCase(name)){
			request.setCharacterEncoding("UTF-8");
			chain.doFilter(request, response);
		}else{
			CharsetEncodingUtil charsetEncodingUtil=new CharsetEncodingUtil(request);
			chain.doFilter(charsetEncodingUtil, response);
		}
	}
	/**
	 * 初始化方法
	 */
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}


13.CharsetEncodingUtil.java
package com.dan.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class CharsetEncodingUtil extends HttpServletRequestWrapper{
	private HttpServletRequest request;
	public CharsetEncodingUtil(HttpServletRequest request){
		super(request);
		this.request=request;
	}
	public String getParameter(String name) { //name为从页面传过来的请求参数
		String nameValue=request.getParameter(name);
		try{
			//对请求的参数进行转码处理
			if(nameValue!=null){
				nameValue=new String(nameValue.getBytes("ISO-8859-1"),"UTF-8");
			}
			return nameValue;
		}catch(Exception e){
			e.printStackTrace();
		}
		return super.getParameter(name);
	}
}

14.DeployFlowAction.java
package com.hp.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.dan.entity.AskForLeave;
import com.dan.entity.ProcessPicture;
import com.dan.service.IUserService;

public class DeployFlowAction {
	private HttpServletRequest request;
	private List<AskForLeave> taskList;
	private AskForLeave askForLeave;
	private ProcessPicture processPicture;
	private IUserService userService;
	private String title;
	
	/**
	 * 查询审批记录
	 */
	public String audit(){
		request = ServletActionContext.getRequest();
		String auditResult = request.getParameter("auditResult");
		
		//查询待审批的请假记录
		if(2 == askForLeave.getCurrentNodeNum()){ //主管审批
			if("true".equals(auditResult)){
				if(askForLeave.getAflDays() > 10){
					askForLeave.setCurrentNodeNum(4);
				}else{
					askForLeave.setCurrentNodeNum(3);
				}
				askForLeave.setAuditStatus("ZG Approved");
			}else{
				askForLeave.setAuditStatus("ZG Refused");
				askForLeave.setCurrentNodeNum(5);
			}
			
		}else if(3 == askForLeave.getCurrentNodeNum()){ //经理审批
			if("true".equals(auditResult)){
				askForLeave.setAuditStatus("MG Approved");
			}else{
				askForLeave.setAuditStatus("MG Refused");
			}
			askForLeave.setCurrentNodeNum(5);
		}else if(4 == askForLeave.getCurrentNodeNum()){ //老板审批
			if("true".equals(auditResult)){
				askForLeave.setAuditStatus("BG Approved");
			}else{
				askForLeave.setAuditStatus("BG Refused");
			}
			askForLeave.setCurrentNodeNum(5);
		}
		boolean flg = userService.update(askForLeave);
		System.out.println("审批结果:"+flg);
		return null;
	}
	
	/**
	 * 查询审批记录
	 */
	public String query(){
		request = ServletActionContext.getRequest();
		String act = request.getParameter("act");
		String id = request.getParameter("id");
		//查询待审批的请假记录
		askForLeave = userService.findAskForLeave(id);
		title = "";
		if("2".equals(act)){ //主管审批
			title = "主管审批";
		}else if("3".equals(act)){ //经理审批
			title = "经理审批";
		}else if("4".equals(act)){ //老板审批
			title = "老板审批";
		}
		return "audit";
	}
	
	/**
	 * 查看待办任务列表
	 */
	public String waitingTask(){
		taskList = userService.queryWaitForAskForLeave(); //查看待办的请假列表
		return "waitingTask";
	}
	
	/**
	 * 查看已办任务列表
	 */
	public String historyTask(){
		taskList = userService.queryHistoryForAskForLeave(); //查看待办的请假列表
		return "waitingTask";
	}
	
	/**
	 * 查看图片
	 */
	public void showImg() throws Exception{
		request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		InputStream inputStream = new FileInputStream("D:\\twx162737\\test\\qj.png");
		byte[] b = new byte[1024];
		int len = -1;
		try {
			while ((len = inputStream.read(b, 0, 1024)) != -1) {
				response.getOutputStream().write(b, 0, len);
			}
			response.getOutputStream().flush();  
			response.getOutputStream().close(); 
			inputStream.close(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 显示当前活动所在的结点
	 * @return
	 */
	public String showPictureNode(){
		request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		System.out.println("流程当前节点为: "+id);
		processPicture = userService.query(id);
		request.setAttribute("id", processPicture.getId()); //id为0表示当前流程处在开始节点
		request.setAttribute("X", processPicture.getNodeLocation_x());
		request.setAttribute("Y", processPicture.getNodeLocation_y());
		request.setAttribute("width", processPicture.getNodeLocation_w());
		request.setAttribute("height", processPicture.getNodeLocation_h());
		return "showPic";
	}
	/**
	 * 请假申请
	 */
	public String apply() throws Exception{
		this.askForLeave.setAuditStatus("Aplied");
		this.askForLeave.setCurrentNodeNum(2); //设置流程所处的节点为开始节点的下一个节点处
		boolean flg = this.userService.apply(askForLeave);
		System.out.println("提交申请成功与否:"+flg);
		return null;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	public List<AskForLeave> getTaskList() {
		return taskList;
	}
	public void setTaskList(List<AskForLeave> taskList) {
		this.taskList = taskList;
	}
	public AskForLeave getAskForLeave() {
		return askForLeave;
	}
	public void setAskForLeave(AskForLeave askForLeave) {
		this.askForLeave = askForLeave;
	}
	public IUserService getUserService() {
		return userService;
	}
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	public ProcessPicture getProcessPicture() {
		return processPicture;
	}
	public void setProcessPicture(ProcessPicture processPicture) {
		this.processPicture = processPicture;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}
我的工作流demo-2
6.User.java
package com.dan.entity;


import java.io.Serializable;

 
/**
 * 实体类
 * @author zdd
 *
 */
public class User implements Serializable {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Integer id;
	
	private String name;
	
	private String age;
	
	public User(){
		
	}
	
	public User(String name,String age){
		this.name = name;
		this.age = age;
	}

	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}
}

7.AskForLeave.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dan.entity">
	<class name="AskForLeave" table="tb_ask_for_leave">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="aflName"></property>
		<property name="aflDays"></property>
		<property name="auditStatus"></property>
		<property name="firstAuditPeople"></property>
		<property name="secondAuditPeople"></property>
		<property name="aflDesc"></property>
		<property name="currentNodeNum"></property>
		<property name="auditPeople"></property>
	</class>
</hibernate-mapping>

8.ProcessPicture.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dan.entity">
	<class name="ProcessPicture" table="tb_process_picture">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="nodeName"></property>
		<property name="nodeLocation_x"></property>
		<property name="nodeLocation_y"></property>
		<property name="nodeLocation_w"></property>
		<property name="nodeLocation_h"></property>
	</class>
</hibernate-mapping>

9.User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dan.entity">
	<class name="User" table="tb_user">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"></property>
		<property name="age"></property>
		<!-- 多对多 -->
		<!-- <set name="users" cascade="all" table="tb_user_action">
			<key column="actionId"></key>
			<many-to-many class="UserPojo" column="userId"></many-to-many>
		</set> -->
	</class>
</hibernate-mapping>

10.IUserService.java
package com.dan.service;

import java.util.List;

import com.dan.entity.AskForLeave;
import com.dan.entity.ProcessPicture;
import com.dan.entity.User;

public interface IUserService {

	public void addUser(User user);
	public boolean apply(AskForLeave askForLeave);
	public List<AskForLeave> queryWaitForAskForLeave();
	public ProcessPicture  query(String currentNodeNumStr);
	public AskForLeave findAskForLeave(String id);
	public boolean update(AskForLeave askForLeave);
	public List<AskForLeave> queryHistoryForAskForLeave();
}

11.UserService.java
package com.dan.service.impl;

import java.util.List;

import com.dan.dao.IUserDao;
import com.dan.entity.AskForLeave;
import com.dan.entity.ProcessPicture;
import com.dan.entity.User;
import com.dan.service.IUserService;

public class UserService implements IUserService {
	private IUserDao userDao;
	
	@Override
	public void addUser(User user) {
		userDao.addUser(user);
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public boolean apply(AskForLeave askForLeave) {
		return userDao.apply(askForLeave);
	}

	@Override
	public List<AskForLeave> queryWaitForAskForLeave() {
		return userDao.queryWaitForAskForLeave();
	}

	@Override
	public ProcessPicture query(String currentNodeNumStr) {
		Integer currentNodeNum = Integer.valueOf(currentNodeNumStr);
		return userDao.query(currentNodeNum);
	}

	@Override
	public AskForLeave findAskForLeave(String idStr) {
		Integer id = Integer.valueOf(idStr);
		return userDao.findAskForLeave(id);
	}

	@Override
	public boolean update(AskForLeave askForLeave) {
		return userDao.update(askForLeave);
	}

	@Override
	public List<AskForLeave> queryHistoryForAskForLeave() {
		return userDao.queryHistoryForAskForLeave();
	}

}
我的工作流demo-01
1.UserAction.java
package com.dan.action;

import com.dan.entity.User;
import com.dan.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * UserAction类
 * @author zdd
 *
 */
public class UserAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1853360186599729298L;

	private IUserService userService;
	
	private User user;
	//显示添加页面
	public String showAddUser(){
		return "showAddUser";
	}
	
	//添加用户
	public String addUser() throws Exception{
		System.out.println(user.getName()+", "+user.getAge());
		userService.addUser(user);
		
		return "success";
	}
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}

2.IUserDao.java
package com.dan.dao;

import java.util.List;

import com.dan.entity.AskForLeave;
import com.dan.entity.ProcessPicture;
import com.dan.entity.User;

/**
 * UserDao接口
 * @author zdd
 *
 */
public interface IUserDao {
	
	public void addUser(User user);
	public boolean apply(AskForLeave askForLeave);
	public List<AskForLeave> queryWaitForAskForLeave();
	public ProcessPicture query(Integer currentNodeNum);
	public AskForLeave findAskForLeave(Integer id);
	public boolean update(AskForLeave askForLeave);
	public List<AskForLeave> queryHistoryForAskForLeave();
}

3.UserDao.java
package com.dan.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.dan.dao.IUserDao;
import com.dan.entity.AskForLeave;
import com.dan.entity.ProcessPicture;
import com.dan.entity.User;

/**
 * UserDao
 * @author zdd
 *
 */
public class UserDao implements IUserDao {

	//调用注入的sessionFactory
	private SessionFactory sessionFactory;
	
	@Override
	public void addUser(User user) {
		System.out.println(user.getName()+", "+user.getAge());
		Session session = sessionFactory.openSession();
		session.getTransaction().begin();
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean apply(AskForLeave askForLeave) {
		try{
			System.out.println(askForLeave.getAflName()+", "+askForLeave.getAflDays());
			Session session = sessionFactory.openSession();
			session.getTransaction().begin();
			session.save(askForLeave);
			session.getTransaction().commit();
			session.close();
			return true;
		}catch(Exception e){
			return false;
		}
	}

	@Override
	public List<AskForLeave> queryWaitForAskForLeave() {
		Session session = sessionFactory.openSession();
		List<AskForLeave> list = session.createQuery("from AskForLeave where auditStatus in ('Aplied','ZG Approved') ").list();
		return list;
	}

	@Override
	public ProcessPicture query(Integer currentNodeNum) {
		Session session = sessionFactory.openSession();
		ProcessPicture pp = (ProcessPicture) session.createQuery("from ProcessPicture where id = "+currentNodeNum).list().get(0);
		return pp;
	}

	@Override
	public AskForLeave findAskForLeave(Integer id) {
		Session session = sessionFactory.openSession();
		AskForLeave asl = (AskForLeave) session.get(AskForLeave.class, id);
		return asl;
	}

	@Override
	public boolean update(AskForLeave askForLeave) {
		try{
			Session session = sessionFactory.openSession();
			AskForLeave asl = (AskForLeave) session.get(AskForLeave.class, askForLeave.getId());
			asl.setAuditStatus(askForLeave.getAuditStatus());
			asl.setCurrentNodeNum(askForLeave.getCurrentNodeNum());
			session.beginTransaction();
			session.update(asl);
			session.getTransaction().commit();
			return true;
		}catch(Exception e){
			return false;
		}
	}

	@Override
	public List<AskForLeave> queryHistoryForAskForLeave() {
		Session session = sessionFactory.openSession();
		List<AskForLeave> list = session.createQuery("from AskForLeave where auditStatus in ('BG Approved','MG Approved','ZG Refused','MG Refused','BG Refused') ").list();
		return list;
	}

}

4.AskForLeave.java
package com.dan.entity;
/**对应请假表*/
public class AskForLeave {
	private Integer id;
	private String aflName; //请假人
	private Double aflDays; //请假天数
	private String auditStatus; //审批状态Aplied 
	private String firstAuditPeople; //一级审批人
	private String secondAuditPeople; //二级审批人
	private String auditPeople; //审批人
	private String aflDesc; //请假描述
	private Integer currentNodeNum; //流程所处的节点编号
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getAflName() {
		return aflName;
	}
	public void setAflName(String aflName) {
		this.aflName = aflName;
	}
	public Double getAflDays() {
		return aflDays;
	}
	public void setAflDays(Double aflDays) {
		this.aflDays = aflDays;
	}
	public String getAuditStatus() {
		return auditStatus;
	}
	public void setAuditStatus(String auditStatus) {
		this.auditStatus = auditStatus;
	}
	public String getFirstAuditPeople() {
		return firstAuditPeople;
	}
	public void setFirstAuditPeople(String firstAuditPeople) {
		this.firstAuditPeople = firstAuditPeople;
	}
	public String getSecondAuditPeople() {
		return secondAuditPeople;
	}
	public void setSecondAuditPeople(String secondAuditPeople) {
		this.secondAuditPeople = secondAuditPeople;
	}
	public String getAflDesc() {
		return aflDesc;
	}
	public void setAflDesc(String aflDesc) {
		this.aflDesc = aflDesc;
	}
	public Integer getCurrentNodeNum() {
		return currentNodeNum;
	}
	public void setCurrentNodeNum(Integer currentNodeNum) {
		this.currentNodeNum = currentNodeNum;
	}
	public String getAuditPeople() {
		return auditPeople;
	}
	public void setAuditPeople(String auditPeople) {
		this.auditPeople = auditPeople;
	}
}

5.ProcessPicture.java
package com.dan.entity;
/**
 * 流程图持久类
 */
public class ProcessPicture {
	private Integer id;
	private String nodeName; //节点名称
	private Integer nodeLocation_x; //节点x坐标
	private Integer nodeLocation_y; //节点y坐标
	private Integer nodeLocation_w; //宽度
	private Integer nodeLocation_h; //高度
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getNodeName() {
		return nodeName;
	}
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}
	public Integer getNodeLocation_x() {
		return nodeLocation_x;
	}
	public void setNodeLocation_x(Integer nodeLocation_x) {
		this.nodeLocation_x = nodeLocation_x;
	}
	public Integer getNodeLocation_y() {
		return nodeLocation_y;
	}
	public void setNodeLocation_y(Integer nodeLocation_y) {
		this.nodeLocation_y = nodeLocation_y;
	}
	public Integer getNodeLocation_w() {
		return nodeLocation_w;
	}
	public void setNodeLocation_w(Integer nodeLocation_w) {
		this.nodeLocation_w = nodeLocation_w;
	}
	public Integer getNodeLocation_h() {
		return nodeLocation_h;
	}
	public void setNodeLocation_h(Integer nodeLocation_h) {
		this.nodeLocation_h = nodeLocation_h;
	}
	
}

自己整合的--S2SH+JBPM4.4 demo--05
25.success.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=UTF-8">
<title>success</title>
</head>
<body>
	success!!!
</body>
</html>

26.deploy.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!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>
	<c:forEach var="deployProcess" items="deployProcesses">
		<tr>
			<td>${deployProcess.id}</td>
			<td>${deployProcess.name}</td>
			<td>${deployProcess.version}</td>
			<td><a href="">流程删除</a></td>
			<td><a href="">启动流程</a></td>
		</tr>
	</c:forEach>
</body>
</html>

27.error.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=UTF-8">
<title>error</title>
</head>
<body>
	error!!!
</body>
</html>


28.jar包有:
activation.jar
antlr-2.7.6.jar
aopalliance.jar
aspectjrt.jar
aspectjweaver.jar
backport-util-concurrent-3.1.jar
cglib-2.2.jar
commons-collections-3.1.jar
commons-dbcp.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging.jar
commons-logging-1.0.4.jar
commons-pool.jar
dom4j-1.6.1.jar
ehcache-1.5.0.jar
freemarker-2.3.15.jar
hibernate3.jar
james-2.3.2.jar
javassist-3.9.0.GA.jar
jbpm.jar
jdom.jar
jstl.jar
jta-1.1.jar
junit-4.4.jar
jxl.jar
mail.jar
mysql-connector-java-5.1.15-bin.jar
ognl-2.7.3.jar
org.springframework.aop-3.0.5.RELEASE.jar
org.springframework.asm-3.0.5.RELEASE.jar

org.springframework.aspects-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.context.support-3.0.5.RELEASE.jar

org.springframework.context-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar

org.springframework.expression-3.0.5.RELEASE.jar
org.springframework.jdbc-3.0.5.RELEASE.jar
org.springframework.orm-3.0.5.RELEASE.jar
org.springframework.transaction-3.0.5.RELEASE.jar

org.springframework.web.struts-3.0.5.RELEASE.jar
org.springframework.web-3.0.5.RELEASE.jar
proxool-0.9.0RC3.jar

servlet-api.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar

standard.jar
struts2-core-2.1.8.1.jar
struts2-spring-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar
自己整合的--S2SH+JBPM4.4 demo--04
20.struts.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <!-- 将struts2的Action交给Spring管理 -->
    <constant name="struts.objectFactory" value="spring" />
	<!-- 配置其他常量 -->
	<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	
	<!-- 用户模块的Action配置 -->
	<package name="struts_user" extends="struts-default" namespace="/user">
		<action name="user" class="userAction">
			<result name="success" type="redirect">/index.jsp</result>
			<!-- <result name="input">/login.jsp</result> -->
		</action>
	</package>
	
</struts>

21.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" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
   <filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>charsetEncoding</filter-name>
    <filter-class>com.dan.util.CharsetEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>charsetEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-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>
</web-app>

22.addUser.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=UTF-8">
<title>添加用户</title>
</head>
<body>
	<h3>添加用户</h3>
	<form action="user/user!addUser" method="post">
		姓名: <input type="text" id="name" name="user.name"/><br /><br />
		年龄: <input type="text" id="age" name="user.age"/><br /><br />
		<input type="submit" value="添加"/>
	</form>
</body>
</html>

23.index.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=UTF-8">
<title>welcome</title>
<style type="text/css">
	#top{
		width:99%;
		height:50px;
		float:top;
		border-color:blue;
		border:1px solid;
	}
	#main{
		width:100%;
		height:84%;
		float:top;
		position:absolute;
	}
	#leftFrame{
		width:10%;
		height:100%;
		border:1px solid;
		float:left;
	}
	#rightFrame{
		width:88%;
		height:100%;
		border:1px solid;
		float:left;
	} 
	#treeDiv{
		margin-left:10%;
		background-color:white;
	}
	div{
		font-size:14px;
	}
	#bg_frame{
		background-color:lightblue;
	}
</style>
</head>
<body>
	<div id="top">事务管理系统</div>
	<div id="main">
		<div id="leftFrame">
			<div>
				<div id="bg_frame">我的代办任务</div>
				<div id="treeDiv"><a href="">审批处理</a></div>
			</div>
			<div>
				<div id="bg_frame">日常任务</div>
				<div id="treeDiv"><a href="qingjia.jsp">请假</a></div>
			</div>
		</div>
		<div id="rightFrame">
			主窗体内容
		</div> 
	</div>
</body>
</html>

24.qingjia.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=UTF-8">
<title>请假</title>
</head>
<body>

</body>
</html>
自己整合的--S2SH+JBPM4.4 demo--03
13.applicationContext_db.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">
	<!-- 配置sesionFactory-->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
		<property name="mappingLocations">
			<list>
				<value>classpath:jbpm.execution.hbm.xml</value>
				<value>classpath:jbpm.history.hbm.xml</value>
				<value>classpath:jbpm.identity.hbm.xml</value>
				<value>classpath:jbpm.repository.hbm.xml</value>
				<value>classpath:jbpm.task.hbm.xml</value>
			</list>
		</property>
	</bean> 
	<!-- 配置事物管理器bean -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<aop:config>
		<aop:pointcut id="entryPointMethod" expression="execution(* com.dan.service.impl.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="entryPointMethod"/>
	</aop:config>
	<aop:config>
		<aop:pointcut id="jobspacePointMethod" expression="execution(* com.dan.service.impl.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="jobspacePointMethod"/>
	</aop:config>
	<!-- 配置事物 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="create*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="add*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="delete*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="update*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="apply*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
			<tx:method name="save*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" />
		</tx:attributes>
	</tx:advice>
	<!-- 集成jbpm -->
	<bean id="springHelper" class="org.jbpm.pvm.internal.processengine.SpringHelper">
		<property name="jbpmCfg" value="jbpm.cfg.xml" />  
	</bean>
	<bean id="processEngine" factory-bean="springHelper" factory-method="createProcessEngine" />
</beans>

14.applicationContext_service.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">
	<!--配置service层bean -->
	<bean id="userService" class="com.dan.service.impl.UserService">
		<property name="userDao" ref="userDao"></property>
	</bean>
	
</beans>

15.ehcache.xml
<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
    <cache name="com.happiness.pojo.APojo"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />
</ehcache>

16.hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 加载proxool数据库连接池 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
		<property name="hibernate.proxool.pool_alias">hp</property>
		<property name="hibernate.proxool.xml">proxool.xml</property>
		<!-- 自动生成数据表文件 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!--指定数据库语言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 显示sql语句 -->
		<property name="show_sql">true</property>
		
		<!-- 加载二级缓存 -->
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		
		<!-- 加载hibernate映射文件 -->
		<!-- <mapping resource="com/tdtech/pdm/create/pojo/DQDocumentPojo.hbm.xml" /> -->
		<mapping resource="com/dan/entity/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>

17.jbpm.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

<jbpm-configuration>
  <import resource="jbpm.default.cfg.xml" />
  <import resource="jbpm.businesscalendar.cfg.xml" />
  <import resource="jbpm.tx.spring.cfg.xml" />
  <import resource="jbpm.jpdl.cfg.xml" />
  <import resource="jbpm.bpmn.cfg.xml" />
  <import resource="jbpm.identity.cfg.xml" />
</jbpm-configuration>

18.proxool.xml
<?xml version="1.0" encoding="UTF-8"?>
<something-else-entirely>
	<proxool>
		<!--连接池的别名 -->
		<alias>hp</alias>
		<!--proxool只能管理由自己产生的连接 -->
		<driver-url>jdbc:mysql://10.23.28.231:3306/db_ssh2jbpm</driver-url>
        <!-- JDBC驱动程序-->
		<driver-class>com.mysql.jdbc.Driver</driver-class>
		<driver-properties>
			<property name="user" value="root" />
			<property name="password" value="Td123456" />
		</driver-properties>
		
		<!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回 收,超时的销毁 -->
		<house-keeping-sleep-time>90000</house-keeping-sleep-time>
		<!-- 指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的 用户连接就不会被接受 -->
		<simultaneous-build-throttle>20</simultaneous-build-throttle>
		<!-- 最少保持的空闲连接数 -->
		<prototype-count>5</prototype-count>
		<!-- 允许最大连接数,超过了这个连接,再有请求时,就排在队列中等候,最大的 等待请求数由maximum-new-connections决定 -->
		<maximum-connection-count>100</maximum-connection-count>
		<!-- 最小连接数 -->
		<minimum-connection-count>10</minimum-connection-count>
		<!-- add time: 2013-5-14 begin -->
		<test-before-use>true</test-before-use>
		<test-after-use>true</test-after-use>
		<house-keeping-test-sql>SELECT CURRENT_USER</house-keeping-test-sql>
		<!-- add time: 2013-5-14 end -->
	</proxool>
</something-else-entirely>

19.struts.properties
struts.multipart.maxSize=314572800
自己整合的--S2SH+JBPM4.4 demo--02
8.CharsetEncodingFilter.java
package com.dan.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharsetEncodingFilter implements Filter{
	/**
	 * 销毁方法
	 */
	public void destroy() {
		
	}
	/**
	 * 字符乱码处理方法
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response=(HttpServletResponse)res;
		HttpServletRequest request=(HttpServletRequest)req;
		String name=request.getMethod();  //name为请求方式
		if("post".equalsIgnoreCase(name)){
			request.setCharacterEncoding("UTF-8");
			chain.doFilter(request, response);
		}else{
			CharsetEncodingUtil charsetEncodingUtil=new CharsetEncodingUtil(request);
			chain.doFilter(charsetEncodingUtil, response);
		}
	}
	/**
	 * 初始化方法
	 */
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}

9.CharsetEncodingUtil.java
package com.dan.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class CharsetEncodingUtil extends HttpServletRequestWrapper{
	private HttpServletRequest request;
	public CharsetEncodingUtil(HttpServletRequest request){
		super(request);
		this.request=request;
	}
	public String getParameter(String name) { //name为从页面传过来的请求参数
		String nameValue=request.getParameter(name);
		try{
			//对请求的参数进行转码处理
			if(nameValue!=null){
				nameValue=new String(nameValue.getBytes("ISO-8859-1"),"UTF-8");
			}
			return nameValue;
		}catch(Exception e){
			e.printStackTrace();
		}
		return super.getParameter(name);
	}
}

10.DeployFlowAction.java
package com.hp.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.RepositoryService;

public class DeployFlowAction {
	private ProcessEngine processEngine;
	private ExecutionService executionService;
	private HttpServletRequest request;
	private List<ProcessDefinition> deployProcesses;
	/**
	 * 部署流程定义
	 */
	public String deploy() throws Exception{
		System.out.println("部署流程定义-action");
		RepositoryService repositoryService = this.processEngine.getRepositoryService();
		//部署流程定义
		repositoryService.createDeployment().addResourceFromClasspath("com/hp/test/process.jpdl.xml").deploy();
		deployProcesses = repositoryService.createProcessDefinitionQuery().list();
		return null;
	}
	/**
	 * 启动流程 
	 */
	public String startProcess(){
		executionService = this.processEngine.getExecutionService();
		executionService.startProcessInstanceById(request.getParameter("id"));
		return null;
	}
	public ProcessEngine getProcessEngine() {
		return processEngine;
	}
	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
	}
	public ExecutionService getExecutionService() {
		return executionService;
	}
	public void setExecutionService(ExecutionService executionService) {
		this.executionService = executionService;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	public List<ProcessDefinition> getDeployProcesses() {
		return deployProcesses;
	}
	public void setDeployProcesses(List<ProcessDefinition> deployProcesses) {
		this.deployProcesses = deployProcesses;
	}
}


11.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="processEngine" ref="processEngine"></property>
	</bean>
	<bean id="userAction" class="com.dan.action.UserAction">
		<property name="userService" ref="userService"></property>
		<property name="processEngine" ref="processEngine"></property>
	</bean>
</beans>

12.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">
	<!-- 配置HibernateTemplate bean -->
	<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean> -->
	<!-- 配置Dao层bean -->
	<!-- <bean id="dQDocumentDaoImpl" class="com.tdtech.pdm.create.dao.impl.DQDocumentDaoImpl">
		<property name="hibernateTemplate" ref="hibernateTemplate"></property>
	</bean> -->
	<bean id="userDao" class="com.dan.dao.impl.UserDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>
自己整合的--S2SH+JBPM4.4 demo--01
1.UserAction.java
package com.dan.action;

import org.jbpm.api.ProcessEngine;

import com.dan.entity.User;
import com.dan.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * UserAction类
 * @author zdd
 *
 */
public class UserAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1853360186599729298L;

	private IUserService userService;
	
	private User user;
	
	private ProcessEngine processEngine;
	
	//显示添加页面
	public String showAddUser(){
		return "showAddUser";
	}
	
	//添加用户
	public String addUser() throws Exception{
		System.out.println(user.getName()+", "+user.getAge());
		userService.addUser(user);
		
		return "success";
	}

	//测试JBPM
	public String testJbpm() throws Exception{
		System.out.println("整合成功");
		System.out.println("processEngine =========== " + processEngine);
		return "success";
	}
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public ProcessEngine getProcessEngine() {
		return processEngine;
	}

	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
	}
}


2.IUserDao.java
package com.dan.dao;

import com.dan.entity.User;

/**
 * UserDao接口
 * @author zdd
 *
 */
public interface IUserDao {
	
	public void addUser(User user);

}

3.UserDao.java
package com.dan.dao.impl;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.dan.dao.IUserDao;
import com.dan.entity.User;

/**
 * UserDao
 * @author zdd
 *
 */
public class UserDao implements IUserDao {

	//调用注入的sessionFactory
	private SessionFactory sessionFactory;
	
	@Override
	public void addUser(User user) {
		System.out.println(user.getName()+", "+user.getAge());
		Session session = sessionFactory.openSession();
		session.getTransaction().begin();
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}

4.User.java
package com.dan.entity;


import java.io.Serializable;

 
/**
 * 实体类
 * @author zdd
 *
 */
public class User implements Serializable {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Integer id;
	
	private String name;
	
	private String age;
	
	public User(){
		
	}
	
	public User(String name,String age){
		this.name = name;
		this.age = age;
	}

	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}
}

5.User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dan.entity">
	<class name="User" table="tb_user">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"></property>
		<property name="age"></property>
		<!-- 多对多 -->
		<!-- <set name="users" cascade="all" table="tb_user_action">
			<key column="actionId"></key>
			<many-to-many class="UserPojo" column="userId"></many-to-many>
		</set> -->
	</class>
</hibernate-mapping>

6.IUserService.java
package com.dan.service;

import com.dan.entity.User;

public interface IUserService {

	public void addUser(User user);
	
}


7.UserService.java
package com.dan.service.impl;

import com.dan.dao.IUserDao;
import com.dan.entity.User;
import com.dan.service.IUserService;

public class UserService implements IUserService {
	private IUserDao userDao;
	
	@Override
	public void addUser(User user) {
		userDao.addUser(user);
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

}
java枚举类型的使用--demo java枚举类型的使用--demo
1. 
package com.dwr.test;

public enum EnumDemo {
	//定义6个枚举类EnumDemo实例BLACK, RED, BLUE, YELLOW, WHITE
	BLACK,
	RED("红色", 1), 
	BLUE("蓝色", 2),
	GREEN("绿色", 3),
	WHITE("白色", 4),
	GREY(5);
	//定义枚举的成员变量
	int colorvalue;
	String colorname; 
	//定义枚举类的构造方法
	EnumDemo(){
		
	}
	EnumDemo(int value){
		this.colorvalue = value;
	}
	EnumDemo(String name, int value){
		this.colorname = name;
		this.colorvalue = value;
	}
}


2.
package com.dwr.test;

public class TestEnum {
	public static void main(String[] args) {
		System.out.println(EnumDemo.RED.colorname+","+EnumDemo.RED.colorvalue);
		System.out.println(EnumDemo.BLUE.colorname+","+EnumDemo.BLUE.colorvalue);
		System.out.println(EnumDemo.GREEN.colorname+","+EnumDemo.GREEN.colorvalue);
		System.out.println(EnumDemo.WHITE.colorname+","+EnumDemo.WHITE.colorvalue);
		System.out.println(EnumDemo.BLACK.name()+","+EnumDemo.BLACK.colorvalue);
		System.out.println(EnumDemo.GREY.name()+","+EnumDemo.GREY.colorvalue);
	}
	
}
Global site tag (gtag.js) - Google Analytics