kingforce 发表于 2017-2-3 10:11:07

Tomcat 5.5.20配置JNDI数据源

在tomcat的conf/server.xml中的<GlobalNamingResources>元素中添加如下内容:

<GlobalNamingResources>

<Resource
    name="jdbc/sqlservertest"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="45"
    username="sa"
    maxWait="180"
    driverClassName="net.sourceforge.jtds.jdbc.Driver"
    password="123456"
    url="jdbc:jtds:sqlserver://localhost:1433/test"
    removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
    testOnReturn="true" testWhileIdle="true"/>

<Resource
    name="jdbc/mysqltest"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="45"
    username="root"
    maxWait="180"
    driverClassName="com.mysql.jdbc.Driver"
    password="123456"
    url="jdbc:mysql://localhost:3306/test"
    removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
    testOnReturn="true" testWhileIdle="true"/>

</GlobalNamingResources>

以上配置了两个全局数据源,一个叫jdbc/sqlservertest,是SQLServer2000的,一个叫:jdbc/mysqltest,是mysql的


然后在web程序中写一个jsp:内容如下
<%@page import="java.util.*,javax.naming.*,java.sql.*,javax.sql.*" %>
<%@page contentType="text/html;charset=BIG5"%>
<%
    Context ctx = new InitialContext();
    String strLookup = "java:comp/env/jdbc/mysqltest2";
    DataSource ds =(DataSource) ctx.lookup(strLookup);
    Connection con = ds.getConnection();
    if (con != null){
      out.print("success");
    }else{
      out.print("failure");
    }
%>


然后将做个web工程发布到tomcat下;我用了两种方式发布:一种是war包的方式,一种是在server.xml中添加一个Context;
下面分别说说两种发布方式的区别:

war包方式:
如果要用war包方式发布web应用程序,又要使用JNDI数据源的话,要在你的web工程的META-INF文件夹下设置web项目的Context内容:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/test">
    <ResourceLink global="jdbc/mysqltest" name="jdbc/mysqltest2" type="javax.sql.DataSource"/>
</Context>

global:就是tomcat的server.xml中配置的全局数据源名称。
name:就是你的web项目中要用的那个那个数据源的名称:也就是jsp中写的那个mysqltest2名称;


在server.xml中添加context的方式:
直接在server.xml中的<host></host>中添加如下内容:
<Context path="/test" docBase="c:/test" debug="0" reloadable="true">
       <ResourceLink global="jdbc/mysqltest" name="jdbc/huodong2" type="javax.sql.DataSource"/>
</Context>
页: [1]
查看完整版本: Tomcat 5.5.20配置JNDI数据源