在 Jetty 容器中配置 JNDI 資料來源,可讓 Web 應用透過 java:comp/env/jdbc/... 查找 DataSource,實現資料庫連線池共享與環境解耦。本文以 Maven 專案、H2 資料庫、Eclipse IDE 為例,完整示範從建立資料表到 Jetty 整合的流程。
C:\jtools\h2\bin> java -cp h2-1.4.188.jar org.h2.tools.Server
# 啟動 TCP/PG/Web Console,瀏覽器開啟 https://localhost:8082
jdbc:h2:tcp://localhost/~/jcgdb,用戶 sa,密碼空白。CREATE CACHED TABLE PUBLIC.JCGEXAMPLE (
ID INTEGER,
ARTICLE_NAME VARCHAR(255)
);
INSERT INTO JCGEXAMPLE VALUES (1, 'Jetty JNDI Example');
INSERT INTO JCGEXAMPLE VALUES (2, 'Jetty JMX Example');

Group Id: com.ch.snippets.enterprise
Artifact Id: jetty-jndi-demo
Packaging: war
pom.xml 關鍵依賴:
<dependencies>
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-server</artifactId><version>9.3.2.v20150730</version></dependency>
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-webapp</artifactId><version>9.3.2.v20150730</version></dependency>
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-plus</artifactId><version>9.3.2.v20150730</version></dependency>
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-jndi</artifactId><version>9.3.2.v20150730</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>1.4.188</version></dependency>
</dependencies>
jetty-plus 與 jetty-jndi 模組必須同時在 classpath。jetty.xml 或 WEB-INF/jetty-env.xml 定義 New<Resource>,指定 name="jdbc/jcgdb、type=javax.sql.DataSource、H2 連線參數。web.xml 需宣告 <resource-ref> 映射至 java:comp/env/jdbc/jcgdb,Jetty 才會將資源綁定至 JNDI 子上下文。完成部署後,應用即可透過 @Resource(lookup="java:comp/env/jdbc/jcgdb") 或 InitialContext.lookup() 取得 DataSource。