第一步:配置WEB工程的WEB.XMLjava
<resource-ref> <description>DB Connection</description> <res-ref-name>TEST_DATASOURCE</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
第二步:配置Tomcat对应的server.xml(如下以ORACLE为例,其余DB同理)web
<Context docBase="E:\dev\apps\apache-tomcat-7.0.42\webapps\Test" path="/Test" reloadable="true" source="org.eclipse.jst.jee.server:Test"> <Resource name="TEST_DATASOURCE" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@IP:端口:数据库名称" username="用户名" password="密码" maxActive="20" maxIdle="2" maxWait="-1"/> </Context>
第三步:贴上我工程JNDI部分示例代码sql
static DataSource getDataSource(String dsName) { DataSource ds = null; try { if (ServerDetector.isTomcat()) { dsName = "java:comp/env/" + dsName; } ds = (DataSource)JNDIUtil.getInitialContext().lookup(dsName); } catch (NamingException e) { throw new DataAccessException(e); } if (null == ds) { throw new DataAccessException("data source[" + dsName + "] is null"); } return ds; }
注意事项:数据库
一、上述的数据源名称TEST_DATASOURCE必定要一致!apache
二、server.xml中配置的内容,会在myeclipse执行clean操做的时候强制执行还原server.xml内容的操做,必定要记得从新配置!tomcat