1. 在tomcat的安裝檔案夾下conf檔案夾下的context.xml檔案加入例如以下代碼:
<Resource name="jdbc/course" auth="Container"
//這個name是非常關鍵的。由于web.xml檔案裡也須要用到,在jsp中連接配接資料源也須要用到。
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password="root"
maxIdle="5"
maxWait="5000"
maxActive="10"/></context>
2. 在lib目錄下加入連接配接資料庫的jar包。
3. 在web project項目course配置web.xml,在Web-app之間加入例如以下代碼:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/course</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4. 在jsp中寫連接配接代碼:
Context initctx =new InitialContext();
Context envctx = (Context)initctx.lookup("java:comp/env/");
DataSource ds = (DataSource)envctx.lookup("jdbc/course");
Connection conn = ds.getConnection();