1:struts配置文件里配置《数据源》
<data-source key="date" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClass" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://localhost:3306/test" />
<set-property property="initialSize" value="2" /><!-- 初始华二个池 -->
<set-property property="maxActive" value="4" /><!-- 最多有四个池-->
<set-property property="username" value="root" />
<set-property property="password" value="java" />
</data-source>
2:写个DBManager类,
public static DataSource ds = null;
public static Connection getConnection() throws SQLException{
return ds.getConnection();
}
3:在struts插件中写
System.out.println("StartUpPlugin.init()");
ServletContext application=as.getServletContext();
Enumeration e=application.getAttributeNames();
String path=as.getServletContext().getRealPath("/");
//System.out.println(path);//F:/apache-tomcat-6.0.26/webapps/str/
DataSource ds=(DataSource) application.getAttribute("data");//struts配置文件中data
DBManager.ds=ds;//这样做的话,可以服务启动的时候就加载(数据库连接池)
try {
Connection c1=ds.getConnection();
System.out.println("1:"+c1);
System.out.println("2:"+ds.getConnection());
System.out.println("3:"+ds.getConnection());
System.out.println("4:"+ds.getConnection());
//配置连接池里最多是四个,所以程序停在这里了,等待上面的退出连接池
//System.out.println("5:"+ds.getConnection());
} catch (SQLException e1) {
e1.printStackTrace();
}
while(e.hasMoreElements()){
String name=(String) e.nextElement();
Object value=application.getAttribute(name);
System.out.println("name="+name+",value="+value+"/n"+name.getClass().getName());
}