1、修改TOMCAT_HOME/conf/context.xml
在<Context></Context>中加入
<Resource name="jdbc/teacher"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/hibernate"/>
2、在创建的web工程中WEB-INF/web.xml中添加
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/teacher</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
3、把mysql的jdbc——jar文件复制到工程
WEB-INF/lib目录下,编写测试jsp文件
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<HTML>
<HEAD>
<TITLE>JSP测试页面</TITLE>
</HEAD>
<BODY>
<%out.println("<h1>Hello,test JNDI ! </h1>");%>
<%
Context ctx = new InitialContext();
Context envctx = (Context) ctx.lookup("java:comp/env");
DataSource ds = (DataSource) envctx.lookup("jdbc/teacher");
Connection conn=ds.getConnection();
Statement st=conn.createStatement();
String sql="select * from t_teacher";
ResultSet rs=st.executeQuery(sql);
while(rs.next()) {
%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<br>
<%
}%>
<%out.print("使用jdbc驱动操作数据库操作成功,恭喜你");%>
<%rs.close();
st.close();
conn.close();
%>
</BODY>
</HTML>