论坛首页 Java企业应用论坛

Birt的Servlet扩展

浏览 6042 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2006-11-20  
由于不想用Birt默认的Viewer,所以参考官方的例子用Servlet扩展了!

BirtEngine代码如下:
package com.yjga.birt;

import java.util.logging.Level;

import javax.servlet.ServletContext;

import org.eclipse.birt.core.exception.BirtException;
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.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {

	private static IReportEngine birtEngine = null;

	public static synchronized void initBirtConfig() {
		
	}

	public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
		
		EngineConfig config = new EngineConfig();
		config.setLogConfig(sc.getRealPath("/logs"), Level.FINE);
	
		config.setEngineHome("");
		IPlatformContext context = new PlatformServletContext(sc);
		config.setPlatformContext(context);
		
		//Register new image handler 解决了读取图片时的路径问题
		HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );
		emitterConfig.setActionHandler( new HTMLActionHandler( ) );
		HTMLServerImageHandler imageHandler = new HTMLServerImageHandler( );
		emitterConfig.setImageHandler( imageHandler );
		config.getEmitterConfigs( ).put( "html", emitterConfig ); //-NLS-1$


		try {
			Platform.startup(config);
		} catch (BirtException e) {
			e.printStackTrace();
		}

		IReportEngineFactory factory = (IReportEngineFactory) Platform
				.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
		birtEngine = factory.createReportEngine(config);
		return birtEngine;
	}

	public static synchronized void destroyBirtEngine() {
		if (birtEngine == null) {
			return;
		}
		birtEngine.shutdown();
		Platform.shutdown();
		birtEngine = null;
	}

	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}

	
}


AjzsServlet代码如下:
package com.yjga.birt;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

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

import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;

import com.yjga.util.DateUtil;

public class AjzsServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	private IReportEngine birtReportEngine = null;
	protected static Logger logger = Logger.getLogger("org.eclipse.birt");

	public AjzsServlet() {
		super();
	}

	/**
	 * Destruction of the servlet.
	 */
	public void destroy() {
		super.destroy();
		BirtEngine.destroyBirtEngine();
	}

	/**
	 * The doGet method of the servlet.
	 * 
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		HashMap parmDetails = new HashMap();

		
		// get report name and launch the engine
		resp.setContentType("text/html");
		// resp.setContentType( "application/pdf" );
		// resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
		//得到参数并放入paramsList集合
		String reportName = req.getParameter("ReportName");
		String bm = new String(req.getParameter("bm").getBytes("ISO8859_1"),"GB2312");
		String sj1 = req.getParameter("sj1");
		String sj2 = req.getParameter("sj2");
		List paramsList = new ArrayList();
		if (bm != null && !bm.equals("") && !bm.equals("null"))
			paramsList.add(bm);
		paramsList.add(sj1);
		paramsList.add(sj2);
		
		ServletContext sc = req.getSession().getServletContext();
		this.birtReportEngine = BirtEngine.getBirtEngine(sc);
		
		// setup image directory
		HTMLRenderContext renderContext = new HTMLRenderContext();
		renderContext.setBaseImageURL(req.getContextPath() + "/report/images");
		renderContext.setImageDirectory(sc.getRealPath("/report/images"));

		//logger.log(Level.FINE, "image directory "
		//		+ sc.getRealPath("/report/images"));
		//System.out.println(renderContext.getBaseImageURL());
		//System.out.println(renderContext.getImageDirectory());

		HashMap<String, HTMLRenderContext> contextMap = new HashMap<String, HTMLRenderContext>();
		contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
				renderContext);

		IReportRunnable design;
		try {
			// Open report design
			design = birtReportEngine.openReportDesign(sc
					.getRealPath("/report")
					+ "/" + reportName);
			
			//以下是将报表里的参数和传递进来的参数匹配然后放到parmDetails集合中
			IGetParameterDefinitionTask taskParam = birtReportEngine.createGetParameterDefinitionTask( design );
			Collection params = taskParam.getParameterDefns( true );

			Iterator iter = params.iterator();
			Iterator iterList = paramsList.iterator();
			// Iterate over all parameters
			while ( iter.hasNext() && iterList.hasNext() )
			{
				IParameterDefnBase param = (IParameterDefnBase) iter.next( );
				// Parameters are not in a group
				IScalarParameterDefn scalar = (IScalarParameterDefn) param;
				if(scalar.getName().equals("bm")){
					String paramList = (String)iterList.next();
					parmDetails.put( scalar.getName(),paramList);
					//System.out.println(scalar.getName() + " " + paramList);
				}else{
					Date paramList = new Date();
					try{
						paramList = DateUtil.parse((String)iterList.next(),"yyyy-M-d");
					}catch(Exception e){
						e.printStackTrace();
					}
					parmDetails.put( scalar.getName(),paramList);
					//System.out.println(scalar.getName() + " " + paramList);
				}
			}
			taskParam.close();
			//
			
			// create task to run and render report
			IRunAndRenderTask task = birtReportEngine
					.createRunAndRenderTask(design);
			task.setAppContext(contextMap);
			task.setParameterValues(parmDetails);

			// set output options
			HTMLRenderOption options = new HTMLRenderOption();
			options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
			// options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
			options.setOutputStream(resp.getOutputStream());
			task.setRenderOption(options);

			// run report
			task.run();
			task.close();
		} catch (Exception e) {

			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	/**
	 * The doPost method of the servlet.
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println(" Post does nothing");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
		
	}

	/**
	 * Initialization of the servlet.
	 * @throws ServletException
	 *             if an error occure
	 */
	public void init() throws ServletException {
	}
}


web层只要把参数传递到Servlet即可,但这种扩展通用性还是很差的,代码也比较乱,有待进一步改进!
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics