Tomcat 中配置JNDI连接
JNDI(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API。命名服务将名称和对象联系起来,使得我们可以用名称访问对象。目录服务是一种命名服务,在这种服务里,对象不但有名称,还有属性。
tomcat配置jndi有全局配置和局部配置。大致的有以下三种配置方式。配置前需要先在tomcat的lib目录下放入数据库的驱动jar包。
第一种:全局配置
1)在tomcat的conf文件夹下的context.xml配置文件中加入:
<Resource name="jndi/mybatis" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/appdb" username="root" password="123456" maxActive="20" maxIdle="10" maxWait="10000"/>
<resource-ref> <description>JNDI DataSource</description> <res-ref-name>jndi/mybatis</res-ref-name> <res-ref-type>javax.sql.DataSource</res-ref-type> <res-auth>Container</res-auth></resource-ref>
public void testJNDI() throws NamingException, SQLException{Context ctx = new InitialContext();DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");Connection conn = ds.getConnection();System.out.println(conn.isClosed());}
TestPageAccessURL test = new TestPageAccessURL();test.testJNDI();
<Context path="/demo_jndi" docBase="/demo_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/appdb" maxActive="4"/></Context>
<?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/appdb" username="root" password="123456" maxActive="20" maxIdle="10" maxWait="10000"/></Context>