1.mysql配置。必须为mysql设置密码,如果没有设置密码,驱动无法连接。
2.在tomcat主目录/config/context.xml下添加配置
<Context>
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
maxActive:最大的数据库连接池。设置为-1时,没有限制。maxIdle:最大空闲的数据库连接池保留。设置为-1时,没有限制。
MAXWAIT:最大的时间来等待一个数据库连接变得可用毫秒,在此示例中的10秒。抛出一个异常,如果 超过此超时。设置为-1表示无限期地等待。
username 和password:MySQL的用户名和密码的数据库连接
driverClassName:JDBC驱动程序类。有些地方写的是org.gjt.mm.mysql.Driver,这是以前的写法,不建议这样写
url:用于连接到MySQL数据库的JDBC连接URL。
3.在工程中 创建一个web.xml文件,添加如下内容:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4.编写一个test.jsp文件测试(打印数据库中的数据)
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<sql:query var="rs" dataSource="jdbc/TestDB">
select id, foo, bar from testdata
</sql:query>
<html>
<head>
<title>DB Test</title>
</head>
<body>
<h2>Results</h2>
<c:forEach var="row" items="${rs.rows}">
Foo ${row.foo}<br/>
Bar ${row.bar}<br/>
</c:forEach>
</body>
</html>