日期:2014-05-16  浏览次数:20918 次

如何使用 apache torque (二)
在如何使用 apache torque (一)中已经写过如何在非web应用里面使用torque,这里写如何在web应用里使用torque,以struts为例:
第一步和第二步参考如何使用 apache torque (一)
第三步:初始化torque ,我采用扩展 ActionServlet.java 实现
ExtendActionServlet.java
package com.yh.web.servlet;

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

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

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.struts.action.ActionServlet;

import com.yh.util.DBUtils;
import com.yh.util.FileUtils;
import com.workingdogs.village.Record;

/**
 * @author tylzhuang
 */

public class ExtendActionServlet extends ActionServlet {
	private static Logger log;

	private static final String LOG4J_CONFIG_FILE = "log4j.properties";

	private static final String TORQUE_CONFIG_FILE = "torque.properties";
	
	/** Our internal configuration object */
	public static PropertiesConfiguration commonConfig = null;

	// Initialize global variables
	public void init() throws ServletException {
		synchronized (this.getClass()) {
			super.init();
			ClassLoader cl = this.getClass().getClassLoader();
			InputStream logIn = null;
			InputStream dbIn = null;
			try {					
			         logIn = cl.getResourceAsStream(LOG4J_CONFIG_FILE);
				Properties p = new Properties();
				p.load(logIn);
				PropertyConfigurator.configure(p);
				System.out.println("log4j init success -----------------");	
				//System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.Log4JLogger");
				log = Logger.getLogger(ExtendActionServlet.class); 
				
				log.debug("log4j init success------------" );				
							
				dbIn = cl.getResourceAsStream(TORQUE_CONFIG_FILE);
				PropertiesConfiguration dbConfig = new PropertiesConfiguration();	
				dbConfig.load(dbIn);
				DBUtils.init(dbConfig);
				System.out.println("torque init success----------");

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		finally
		{
			 FileUtils.closeInputStream(logIn);
			 FileUtils.closeInputStream(dbIn);
		}			
			System.out.println("init() Ready to Rumble!");
		}
	}

	// Clean up resources
	public void destroy() {
		super.destroy();
	}

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

		process(request, response);

	}

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

		process(request, response);

	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		super.process(request, response);
	}
}