Tomcat 目录下conf中server.xml中配置:
项目下web.xml中配置:
连接类:
数据库驱动包放在\Tomcat 6.0\lib下
<Context path="/demo" docBase="项目本地路径\WebRoot" reloadable="true">
<Resource name="jdbc/jsp05"
scope="Shareable"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
url="jdbc:mysql://127.0.0.1:3306/test"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password="123"
maxActive="50"
maxIdle="10"
maxWait="-1"/>
</Context>
项目下web.xml中配置:
<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the server.xml file.
</description>
<res-ref-name>jdbc/jsp05</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
连接类:
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JNDIConnection {
public static Connection getConnection(){
Connection conn = null;
try {
InitialContext initCtx = new InitialContext();
Object obj = initCtx.lookup("java:comp/env/jdbc/jsp05");
DataSource ds = (DataSource)obj;
conn = ds.getConnection();
System.out.println("JNDI连接成功");
return conn;
} catch (NamingException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return conn;
}
}
数据库驱动包放在\Tomcat 6.0\lib下