日期:2014-05-16  浏览次数:20454 次

jndi配置
jndi通过容器建立连接,通过连接访问数据库,步骤如下
1、修改tomcat中配置文件-conf/context.xml,配置如下

<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
	
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
	<Resource name="jcptDataSourceJNDI" auth="Container" type="javax.sql.DataSource"
              username="tysp" password="12345678" driverClassName="oracle.jdbc.driver.OracleDriver"
               url="jdbc:oracle:thin:@192.168.1.52:1521:fuxing"/>
    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

</Context>


2、在项目下的WEB-INF/web.xml添加配置代码
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  	<resource-ref>
		<description>Database Source</description>
		<res-ref-name>jcptDataSourceJNDI</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>

3、将数据库驱动jar包放入tomcat的lib中
4、测试,地址引用
<body>
   <%
   		Context initContext = new InitialContext();
		Context envContext = (Context)initContext.lookup("java:/comp/env");
		DataSource ds = (DataSource)envContext.lookup("jcptDataSourceJNDI");
   		Connection conn = ds.getConnection();
   		if(conn==null){
   			out.println("连接失败!");
   		}else{
   			out.println("连接成功!");
   		}
   		Statement stmt = conn.createStatement();
   		ResultSet rs = stmt.executeQuery("select * from t_sys_dept");
   		while(rs.next()){
   			out.println("第一列:"+rs.getString(1));
   		}
    %>
  </body>