Using DataSource in JSP on Tomcat

Tomcat 6.0 instructions
Tomcat 5.5 instructions

使用 Tomcat 6.0, NetBean 6.9.1

1. 確定 mysql-connector-java-{version}-bin.jar 存在以下路徑中

  • CLASSPATH
  • {Tomcat home}/lib

2. 在 META-INF/context.xml 中加入:

<Context antiJARLocking="true" path="/ncku" docBase="ncku" crossContext="true">
    <Resource name="jdbc/NCKU"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="30"
    maxWait="10000"
    removeAbandoned="true"
    removeAbandonedTimeout="60"
    username="root"
    password="root"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/ncku_cross_domain_courses"/>
</Context>
  • name : 為 resource 取名字
  • auth : 預設 Container
  • maxActive : Maximum number of dB connections in pool.
  • maxIdle : Maximum number of idle dB connections to retain in pool.
  • maxWait : Maximum time to wait for a dB connection to become available in ms.

3. 在 WEB-INF/web.xml 中加入:

<resource-ref>
    <res-ref-name>jdbc/NCKU</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Unshareable</res-sharing-scope>
</resource-ref>
  • <res-ref-name> : the name must be the same in context.xml.
  • <res-sharing-scope> : if set to Shareable, a problem may occur when connecting to different DB in a request for servlet1.

4. 在 servlet 中使用

Context initContext = new InitialContext(); 
Context envContext = (Context)initContext.lookup("java:/comp/env"); 
DataSource ds = (DataSource)envContext.lookup("jdbc/NCKU"); 
Connection conn = ds.getConnection();

or

DataSource ds = (DataSource)new InitialContext().lookup("java:/comp/env/jdbc/NCKU"); 
Connection conn = ds.getConnection();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License