1

我正在为 Apache Tomcat 7开发一个自定义Valve ,该 Valve 是在 Apache Tomcat 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>

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

我正在尝试将 JNDI 资源定义为GlobalNamingResources中的全局资源。

<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 级别使用资源来连接到定义的数据库呢?

4

2 回答 2

1

DataSource很长一段时间后,这是我发现从 中获取 Catalina StandardService的唯一方法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());
    }
}
于 2015-05-27T16:55:36.243 回答
1

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

InitialContext initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:jdbc/qgw");
于 2019-04-03T09:09:33.293 回答