IDEA社群版中maven-tomcat外掛配置JNDI資料來源
阿新 • • 發佈:2019-01-03
前言:
由於在學習過程中,教程是使用eplices進行的,而我自己是使用IDEA,所以把配置過程記錄下來
執行環境:OSX 10 、IDEA社群版、Java8、mysql 5.1.38、tomcat7-maven-plugin
步驟:
在Web專案的WEB-INF資料夾中建立context.xml,內容如下
<!-- context.xml --> <?xml version="1.0" encoding='UTF-8' ?> <context> <WatchedResource>WEB-INF/web.xml</WatchedResouurce
在專案的pom.xml檔案中的tomcat7的依賴配置中新增context.xml檔案的路徑,以便Tomcat7能正確引用該檔案:
<!-- pom.xml --> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> .... .... <configuration> ... <contextFile
在web.xml中宣告
<!-- web.xml --> <resource-ref> <res-ref-name>jdbc/msg</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
在java程式碼中獲取資料庫連結:
import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import java.sql.*; ..... Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource)envctx.lookup("jdbc/msg"); Connection conn = ds.getConnection();