如何在Apache Tomcat 7.x中访问Context容器之外的全局JNDI资源?

问题描述 投票:1回答:2

我正在为Apache Tomcat 7开发自定义Valve,该阀门在Apache Tomcat Host container配置文件中的server.xml级别定义。

<Engine defaultHost="localhost" name="Catalina">

    <Realm className="org.apache.catalina.realm.DataSourceRealm" dataSourceName="jdbc/qgw" 
    roleNameCol="role_name" userCredCol="user_pass" userNameCol="user_name" userRoleTable="user_roles" userTable="users"/>

    <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
        <Valve className="org.mycompany.valves.CustomValve"/>
        <Valve className="org.apache.catalina.authenticator.SingleSignOn"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
        pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
    </Host>

</Engine>

阀门需要连接到数据库才能进行一些查询。

我试图在GlobalNamingResources中将JNDI资源定义为全局资源。

<GlobalNamingResources>
    <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" 
    logAbandoned="true" maxActive="25" maxIdle="10" name="jdbc/qgw" 
    password="pass" removeAbandoned="true" removeAbandonedTimeout="300" 
    testOnBorrow="true" type="javax.sql.DataSource" 
    url="jdbc:mysql://localhost/qgw?autoReconnect=true" 
    username="username" validationQuery="SELECT 1"/>
</GlobalNamingResources>

问题是,资源只能在Context容器级别访问,因为在context.xml配置文件中定义了ResourceLink

<ResourceLink global="jdbc/qgw" name="jdbc/qgw" type="javax.sql.DataSource"/> 

显然,当阀门试图通过JNDI获取数据源时

InitialContext initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/qgw");

获取NameNotFoundException

javax.naming.NameNotFoundException: Name comp/env/jdbc/qgw is not bound in this Context

那么,有没有办法使用Host Container级别的资源连接到已定义的数据库?

tomcat7 jndi tomcat-valve
2个回答
1
投票

很长一段时间后,这是我发现获得DataSource,从StandardService获得Catalina container的唯一途径,我不知道这是否是实现这一目标的最佳方式,但它确实有效。

private static final String RESOURCE = "jdbc/qgw";

private DataSource ds;

@Override
protected synchronized void startInternal() throws LifecycleException {
    super.startInternal();

    StandardService service = (StandardService)((StandardEngine)((StandardHost) container).getParent()).getService();
    try {
        // Accesible via GlobalNamingResources too
        //service.getServer().getGlobalNamingResources().findResource(RESOURCE);
        ds = (DataSource)service.getServer().getGlobalNamingContext().lookup(RESOURCE);
        if (ds==null) {
            throw new LifecycleException("Can't get the datasource to connect to database from the valve.");
        }
    } catch (Exception e) {
        container.getLogger().error(e);
        throw new LifecycleException(e.getMessage());
    }
}

1
投票

您还可以尝试在根java级别查找:

InitialContext initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:jdbc/qgw");
© www.soinside.com 2019 - 2024. All rights reserved.