前言:
由于在学习过程中,教程是使用eplices进行的,而我自己是使用IDEA,所以把配置过程记录下来
运行环境:OSX 10 、IDEA社区版、Java8、MySQL 5.1.38、tomcat7-maven-plugin
步骤:
-
在Web项目的WEB-INF文件夹中创建context.xml,内容如下
<?xml version="1.0" encoding='UTF-8' ?>
<context>
<WatchedResource>WEB-INF/web.xml</WatchedResouurce>
<Resource name="jdbc/msg"
auto="container"
type="javax.sql.DataSource"
username="root"
password="Hh13532550193!"
driverClassName="com.mysql.jdbc.Driver"
maxActive="20"
maxIdle="20" />
</context>
-
在项目的pom.xml文件中的tomcat7的依赖配置中添加context.xml文件的路径,以便Tomcat7能正确引用该文件:
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
....
....
<configuration>
...
<contextFile>context.xml文件的路径</contextFile>
</configuration>
....
</plugin>
</plugins>
</build>
-
在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()