JNDI在JAVA WEB工程中的配置

來源:互聯網
上載者:User

標籤:java   jndi資料來源   

第一步:配置WEB工程的WEB.XML

<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同理)

<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部分範例程式碼

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;  }


注意事項:

1、上述的資料來源名稱TEST_DATASOURCE一定要一致!

2、server.xml中配置的內容,會在myeclipse執行clean操作的時候強制執行還原server.xml內容的操作,一定要記得重新設定!





本文出自 “你可以選擇不平凡” 部落格,請務必保留此出處http://ylcodes01.blog.51cto.com/5607366/1916643

JNDI在JAVA WEB工程中的配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.