开发工具:Eclipse J2EE 3.6
运行环境:jdk1.6
部署环境:Tomcat7
数据库连接池用的是dbcp,网上download下来的三个jar包。
把数据库连接池包和jdbc的包放到tomcat的lib下。
新建web project,在META-INF下新建context.xml文件,放入代码(一系列配置)。
<Context path="Prj02" docBase="Prj02" debug="5" crossContext="true" reloadable="true" cachingAllowed="true" cacheMaxSize="20480" cacheTTL="10000"> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/Prj02" auth="Container" type= "javax.sql.DataSource" factory="org.apache.commons.dbcp.BasicDataSourceFactory" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:orcl" username="yff" password="yff" maxActive="100" maxIdle="30" maxWait="10000"> </Resource> </Context>
WebContent下新建index.jsp,放入代码(jdbc连接,sql语句查询)。
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*,org.apache.commons.dbcp.BasicDataSource,javax.rmi.PortableRemoteObject;" %> <% Connection conn = null; Connection m_conn; Statement m_stat; try{ Context ctx = new InitialContext(); Object obj = ctx.lookup("java:comp/env/jdbc/Prj02"); DataSource ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class); conn = ds.getConnection(); if(conn!=null){ m_conn = ds.getConnection(); m_stat = m_conn.createStatement(); ResultSet rs = m_stat.executeQuery("select * from TEST"); while(rs.next()){ out.print("id =" + rs.getInt("id") + ", name=" + rs.getString("name")+" " ); } } }catch (Exception e) { out.print(e.getMessage()); e.printStackTrace(); }finally { if(conn!=null) conn.close(); } %>
部署至Tomcat上。
(oracle内数据)
部署之后的效果。