配置context.xml,在META-INF下新建context.xml,内容如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Context reloadable="true"> 3 <Resource name="jdbc/BookDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" 4 username="root" password="cwx2009" driverClassName="com.mysql.jdbc.Driver" 5 url="jdbc:mysql://127.0.0.1:3306/BookDB?autoReconnect=true"> 6 </Resource> 7 </Context>
配置web.xml
1 <resource-ref> 2 <description>DB Connection</description> 3 <res-ref-name>jdbc/BookDB</res-ref-name> 4 <res-type>javax.sql.DataSource</res-type> 5 <res-auth>Container</res-auth> 6 </resource-ref>
利用jsp页面输出数据库查询结果,查询的主页步骤如下
1 Connection conn; 2 Statement stmt; 3 ResultSet rs; 4 //从数据源中获得数据库连接 5 Context ctx = new InitialContext(); 6 DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/BookDB"); 7 conn = ds.getConnection(); 8 9 //创建一个SQL声明 10 stmt = conn.createStatement(); 11 //查询记录 12 rs = stmt.executeQuery("select id,username,password from schema.admin"); 13 //输出查询结果
省略具体的输出和关闭流的操作