1.在server.xml的</host>节点前加入:
<Context path="/aaa" docBase="test" debug="5" reloadable="true" crossContext="true">
<Resource name="yan/jndi" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@58.116.170.91:1521:oracle"
username="scott" password="tiger" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>
2.在web.xml的<web-app>节点后加入:
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
3.测试代码如下test.jsp:
< %@page contentType="text/html;charset=UTF-8"%>
< %@page import="java.sql.*,javax.sql.DataSource,javax.naming.*"%>
<html>
<body>
<%
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("yan/jndi");
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
while(rs.next()){
out.println(rs.getInt(1) + " "
+ rs.getString(2) + " " + rs.getString(3) + "<br>");
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
注意:在要在apache-tomcat-5.5.17/common/lib中加入class12.jar包
<Context path="/aaa" docBase="test" debug="5" reloadable="true" crossContext="true">
<Resource name="yan/jndi" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@58.116.170.91:1521:oracle"
username="scott" password="tiger" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>
2.在web.xml的<web-app>节点后加入:
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
3.测试代码如下test.jsp:
< %@page
< %@page
<html>
<body>
<%
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("yan/jndi");
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
while(rs.next()){
out.println(rs.getInt(1) + " "
+ rs.getString(2) + " " + rs.getString(3) + "<br>");
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
注意:在要在apache-tomcat-5.5.17/common/lib中加入class12.jar包