|
看了网上的几篇文章,按照上面所介绍的方法都没有配置成功,后来看了tomcat的文档才搞定它。
1.$CATALINA_HOME/conf/server.xml文件中</Host>前加入 <Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true"> <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="20" maxIdle="10" maxWait="-1" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:mysid" /> </Context>
2.WEB-INF/web.xml中加入 <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>
3.测试页面test.jsp <%@ page language="java" pageEncoding="GBK"%> <%@ page import="java.sql.*"%> <%@ page import="javax.naming.*"%> <%@ page import="javax.sql.*"%>
<html> <head> </head> <body> <% Context initContext = new InitialContext(); DataSource ds = (DataSource)initContext.lookup("java:/comp/env/jdbc/TestDB"); Connection conn = ds.getConnection( ); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM user where rownum < 30"); while(rs.next()){ out.print(rs.getString("C_NAME")+" "); out.print(rs.getString("C_EMAIL")+"<br>"); } rs.close(); stmt.close(); conn.close(); %>
</body> </html>
进行以上的步骤时请将相关的jar文件拷贝到$CATALINA_HOME/common/lib下。
以下是tomcat文档中对数据源配置中属性的解释 maxActive: Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your db connections. Set to 0 for no limit.
maxIdle: Maximum number of idle dB connections to retain in pool. Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis configuration parameter.
maxWait: Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely.
username and password: MySQL dB username and password for dB connections
driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver - we recommend using Connector/J though. Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver. url: The JDBC connection url for connecting to your MySQL dB. The autoReconnect=true argument to the url makes sure that the mm.mysql JDBC Driver will automatically reconnect if mysqld closed the connection. mysqld by default closes idle connections after 8 hours.
|
一共有 2 条评论
在web应用程序中META-INF文件夹下建立context.xml文件,内容为:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="-1"
username="scott" password="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
/>
</Context>
也能实现同样的效果