Tomcat 配置 JNDI

JNDI 配置

第一种:全局配置
  
   在tomcat的conf文件夹下的context.xml配置文件中加入:
  
    <!--全局配置-->
<!--
<Resource name="jndi/mybatis"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password="123456"
maxActive="50"
maxIdle="25"
maxWait="50000"/>
-->

第二种:局部配置(不推荐)
   
   在tomcat的server.xml的<host>标签内,添加:
    <!--局部配置-->
<!--
<Context path="/jndi" docBase="/jndi">
   <Resource
name="jndi/mybatis"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
password="123456"
url="jdbc:mysql://localhost:3306/test"
maxActive="4"/>
</Context>
-->

第三种:局部配置
   
在项目的META-INFO下面新建context.xml。加入:
<?xml version="1.0" encoding="UTF-8"?>
   <!--局部配置-->
   <Context>
<Resource name="jndi/mybatis"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password="123456"
maxActive="20"
maxIdle="10"
maxWait="10000"/>
  </Context>

测试程序:
package com.jndi.utils;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class JndiUtils {

private static DataSource ds;

static {
if (ds == null) {
Context ctx;
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");
} catch (NamingException e) {
e.printStackTrace();
}
}
}

public static DataSource getDataSource() {
return ds;
}
}

备注:
总结:如果要配置局部的话,推荐使用第三种方式,这样不依赖tomcat了。但是还是推荐使用第一种方式好,虽然依赖tomat,但是是全局的,而且可以配置
多个。对于以后切换使用方便。
在项目的web.xml中添加的资源引用可有可无。

操作数据库之后,要记得con.close();


 
   

猜你喜欢

转载自luogen33.iteye.com/blog/1860530