【问题标题】:Tomcat 8.5 - Can't access mysql JDBC resource in contextInitialized method of ServletContextListenerTomcat 8.5 - 无法在 ServletContextListener 的 contextInitialized 方法中访问 mysql JDBC 资源
【发布时间】:2017-04-18 19:57:09
【问题描述】:

我的 Web 应用程序有一个这样的 servlet 侦听器:

@WebListener
public class MyContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent e)
    {
        ...
        con = DatasourceProvider.getDatasource("java:comp/env/jdbc/mysql/mydb").getConnection();
        ...
    }
}

我的资源定义没问题,它在 tomcat 7 上运行良好,但是当我升级到 tomcat server 8.5 时,它在启动时抛出异常:

javax.naming.NameNotFoundException: Name [jdbc/mysql/mydb] is not bound in this Context. Unable to find [jdbc].
    at org.apache.naming.NamingContext.lookup(NamingContext.java:816)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
    at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
    at javax.naming.InitialContext.lookup(InitialContext.java:417)
    ...

无论如何,我可以在服务器启动后(在其他 servlet 中)使用相同的代码获得 mysql 连接,没有任何问题。那么问题来了,tomcat启动时出现这个错误的原因是什么?

更新
这是我的虚拟主机配置:

<Host name="my-domain.ir" appBase="/var/www/webapp" >
    <Context path="" docBase="MyWebApp" 
     xmlValidation="false" xmlNamespaceAware="false" crossContext="false" reloadable="false" >
    <Resource name="jdbc/mysql/mydb" auth="Container" type="javax.sql.DataSource"

    initialSize="1" maxTotal="100" maxIdle="2"
    maxWaitMillis="20000" removeAbandonedOnMaintenance="true" removeAbandonedTimeout="300"
    validationQuery="select now();"

    username="myUser" password="myPass" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=UTF-8&amp;characterSetResults=UTF-8&amp;connectionCollation=UTF8_PERSIAN_CI&amp;noAccessToProcedureBodies=true"
    />
    </Context>
</Host>

【问题讨论】:

  • 你能分享你的context.xml吗?
  • @N00bPr0grammer 对于 tomcat 8.5,它是默认的 context.xml,我没有更改它。但是,如果您的意思是我的 Web 应用程序的 Context 元素,我将其添加到更新中

标签: java jdbc initialization connection-pool tomcat8.5


【解决方案1】:

我遇到了和你类似的问题,为此我在我的 Tomcat 的context.xml 中添加了一行(与此类似)以解决问题。

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

以下是指向类似解决方案的问题的链接

Question-1

Question-2

Question-3

希望对你有帮助!!!

【讨论】:

  • 但我不能这样做,因为我有太多的虚拟主机,每个都有自己的资源,我不想也不能让它们全球化。此外,这种情况应该有合理的原因。
  • 现在很有趣,让我看看我能在这上面做什么!
猜你喜欢
  • 1970-01-01
  • 2021-11-05
  • 2014-08-02
  • 2012-06-22
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
相关资源
最近更新 更多