struts2使用數據庫連接池

1

配tomcat

在conf文件夾下server.xml文件

<GlobalNamingResources>   

<Resource name="jdbc/mysql" auth="Container" 

type="javax.sql.DataSource" 

driverClassName="com.mysql.jdbc.Driver" 

url="jdbc:mysql://192.168.1.203:3306/mysql?useUnicode=true&amp;characterEncoding=gbk" username="spider" password="spider" 

maxActive="5" maxIdle="3" maxWait="-1" />

同時

context.xml文件

<ResourceLink global="jdbc/mysql" name="jdbc/mysql" type="javax.sql.DataSource"/>

 

2

工程自己配置文件

META-INF文件夾下context.xml

內容<Context>

<Resource name="jdbc/mysql" auth="Container" 

type="javax.sql.DataSource" 

driverClassName="com.mysql.jdbc.Driver" 

url="jdbc:mysql://192.168.1.203:3306/mysql?useUnicode=true&amp;characterEncoding=gbk" username="spider" password="spider" 

maxActive="5" maxIdle="3" maxWait="-1" />

</Context>

同時在WEB-INF/web.xml增加配置

<resource-ref>

<description>DB Connection</description>

<res-ref-name>jdbc/mysql</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

</web-app>

 

以上2種方法各有優劣,推薦第二種,在java代碼中即可調用連接池了:

try {

   Context env = (Context) new InitialContext().lookup("java:comp/env");

   DataSource ds = (DataSource) env.lookup("jdbc/mysql");

   Connection con = null;

   if (ds == null)

System.err.println("[DbPool]no pool");

else

con = ds.getConnection();

} catch (NamingException ne) {

   ne.printStackTrace();

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章