首先,在tomcat的lib文件夹里加入关于jdbc的jar包。
第二,在tomcat的conf文件夹里找到 context.xml ,在结点 <context> 加上(其中XX为自己的数据库的相关配置):
<Resource name = "jdbc/news" auth="Container"
type="javax.sql.DataSource" maxActive = "100"
maxIdle="30" maxWait = "10000" username = "XX" password = "XX"
driverClassName = "oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:XX"
/>
如果改的时候tomcat已启动,改完后必须重启tomcat;
第三,在自己工程项目的web.xml的<web-app>结点里加上:
<resource-ref>
<description>news DataSource</description>
<res-ref-name>jdbc/news</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
第四,注意在jsp页面导入相关的类:
<%@ page import = "javax.naming.*,javax.sql.*,java.sql.*" %>
我的jsp页面是这样的(页面名称为 test.jsp ,工程名为 news):
<%@ page language = "java" contentType = "text/html;charset=GBK" %>
<%@ page import = "javax.naming.*,javax.sql.*,java.sql.*" %>
<html>
<body>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/news");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from user1");//该sql语句改成你自己的
while (rs.next()) {
out.println(rs.getInt(1) + "<br>");
}
%>
</body>
</html>
最后,启动tomcat,在浏览器里输入 http://localhost:8080/news/test.jsp