1、方式一:在server.xml中配置
1)tomcat安装路径下conf目录下的server.xml,在<GlobalNamingResources>和</GlobalNamingResources>标签之间加入下面的内容:
<Resource name="jdbc/appDS" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/app?rewriteBatchedStatements=true" username="root" password="root" maxActive="100" maxIdle="20" maxWait="10000"/>
2)tomcat安装路径下conf目录下的context.xml,在<Context>和</Context>标签之间加入如下内容:
<ResourceLink name="jdbc/appDS" global="jdbc/appDS" type="javax.sql.DataSource"/>
3)web.xml配置
<resource-ref> <description>app_DataSource</description> <res-ref-name>jdbc/appDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
2、方式二:在context.xml中配置
1)tomcat安装路径下conf目录下的context.xml,在<Context>和</Context>标签之间加入如下内容:
<Resource name="jdbc/appDS" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/app?rewriteBatchedStatements=true" username="root" password="root" maxActive="100" maxIdle="20" maxWait="10000"/>
2)web.xml配置
<resource-ref> <description>app_DataSource</description> <res-ref-name>jdbc/appDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
3、方式三:在项目中的/WebRoot/META-INF/目录下创建一个context.xml文件,内容如下:
<?xml version='1.0' encoding='utf-8'?> <Context> <Resource name="jdbc/appDS" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/app?rewriteBatchedStatements=true" username="root" password="root" maxActive="100" maxIdle="20" maxWait="10000"/> </Context>
web.xml配置如下:
<resource-ref> <description>app_DataSource</description> <res-ref-name>jdbc/appDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
4、如何使用
1)在程序中使用
Context initContext = new InitialContext(); Context ctx = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)ctx.lookup("jdbc/appDS"); Connection conn = ds.getConnection(); //数据操作 //... //关闭资源
2)在spring配置文件中使用
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"><value>java:comp/env/jdbc/appDS</value></property> </bean>