首先在Tomcat7下面的conf/context.xml中的<context>标签中添加属性:
然后在项目中的web.xml中的<web-app>添加如下配置:
MySQL Test App DB Connection jdbc/imooc javax.sql.DataSource Container
值得注意的是Tomcat中的name必须和web.xml中的<res-ref-name>jdbc/imooc</res-ref-name>
保持一致。Jsp页面调用
<%@ page contentType="text/html; charset=UTF-8" %><%@ page import = "javax.naming.*,java.sql.*,javax.sql.*" %><% String result=""; String test=""; Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/imooc"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from imooc_goddess"); while(rs.next()){ result +="\n 第一字段内容:" + rs.getString(2)+""; } conn.close();%><%=result %>
上面的相对应的代码也可以
Context initContext = new InitialContext(); DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/imooc");
但是推荐使用第一种方式。。
原因见: