首先配置Tomcat的context.xml 文件, 增加以下内容:
<Resource name="jdbc/MyDB" <!-- 可以随便定义, 后面用被使用--> auth="Container" <!-- 可以随便定义, 后面用被使用 --> type="javax.sql.DataSource" username="root" <!-- 数据库用户名 --> password="Infosys1234" <!-- 数据库密码 --> driverClassName="com.mysql.jdbc.Driver" <!-- (要把相应的驱动jar包放到$TOMCAT_HOME$/common/lib)--> url="jdbc:mysql://localhost:3306/testdb" <!--服务器地址 数据库名称--> maxActive="8" maxIdle="4" />
再次是配置项目中的web.xml文件,增加以下内容:
<resource-ref> <description> Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the <!-- Context--> configurartion for the web application. </description> <res-ref-name>jdbc/MyDB</res-ref-name> <!-- 与context.xml文件中的名称都应--> <res-type>javax.sql.DataSource</res-type> <!-- 与context.xml文件中的名称都应--> <res-auth>Container</res-auth> <!-- 与context.xml文件中的名称都应--> </resource-ref>
Java 代码中使用如下:
public static Connection getJNDIConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/MyDB"); // 与context.xml文件中的名称都应 Connection conn = null; if (ds != null) { conn = ds.getConnection(); } return conn; }
最后启动服务器
如果抛exception Cannot create JDBC driver of class '' for connect URL 'null'异常,
在server.xml文件的<GlobalNamingResources>标签中加上:
<Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource" username="root" password="Infosys1234" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/testdb" maxActive="8" maxIdle="4" />
即与在Context.xml文件中添加的一致
最后检查驱动有没有配置“driverClassName="com.mysql.jdbc.Driver" 和数据库驱动包是否已经发到Tomcat的lib文件下,再次重新启动服务器。
参考: http://ootabc.iteye.com/blog/407748