我的 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&characterEncoding=UTF-8&characterSetResults=UTF-8&connectionCollation=UTF8_PERSIAN_CI&noAccessToProcedureBodies=true"
/>
</Context>
</Host>