2016-12-04 112 views
1
的contextInitialized方法

我的web应用一个servlet监听器是这样的:的Tomcat 8.5 - 无法访问MySQL JDBC资源中的ServletContextListener

@WebListener 
public class MyContextListener implements ServletContextListener { 

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

我的资源定义是OK &它一直很好它的Tomcat 7,但当我升级到Tomcat服务器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) 
    ... 

总之,使用相同的代码没有任何问题,我可以得到服务器后的Starup MySQL连接(在其他Servlet)。所以问题是,当tomcat启动时导致这个错误的原因是什么?

UPDATE
这里是我的虚拟主机配置:

<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> 
+0

你可以分享你的'context.xml'吗? –

+0

@ N00bPr0grammer它是tomcat 8.5的默认'context.xml'并且我没有改变它。但是,如果你的意思是我的web应用程序的'Context'元素,我把它添加到更新 –

回答

0

我也有类似的问题,因为像你这样的,为此,我加了一条线(与此类似)到我的Tomcat的context.xml解决问题。

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

以下是链接到该点出一个类似的解决方案

Question-1

Question-2

Question-3

希望帮助的问题!

+0

但我不能这样做,因为我有太多的虚拟主机,每个人都有自己的资源,我不想&可以让他们全球化。另外,这种情况应该有合理的理由。 –

+0

现在这很有趣,让我看看我能做些什么呢! –