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&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&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();
}