struts配置数据源

引用

<data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource" key="oracle11">
<set-property property="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<set-property property="url" value="jdbc:oracle:thin:@localhost:1521:WMG"/>
<set-property property="username" value="hibernate"/>
<set-property property="password" value="hibernate"/>
<set-property property="maxActive" value="20"/>
<set-property property="maxIdle" value="4"/>
<set-property property="maxWait" value="4000"/>
<set-property property="autoCommit" value="true"/>
</data-source>
</data-sources>

获取链接代码可以使用一个插件来获得:
package com.mj.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.sql.DataSource;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
public class ConnPool implements PlugIn {
	private static DataSource ds=null;
	
	
	public void destroy() {
		ds=null;
	}

	/**
	 * 初始化获得数据源
	 */
	public void init(ActionServlet servlet, ModuleConfig config)
			throws ServletException {
		ds=(DataSource)servlet.getServletContext().getAttribute("oracle11");
		System.out.println("我是插件=="+ds);
	}
	
	public static Connection getConn(){
		Connection conn=null;
		if(ds!=null){	
			try {
				conn = ds.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conn;
	}

}
	

然后在struts-config.xml里面对插件进行一下注册:
<plug-in className="com.mj.utils.ConnPool"/>

你可能感兴趣的:(java,apache,sql,struts,servlet)