使用Jet的JNDI查找失败与MySQL建立JDBC连接池?

我正在使用带有标准MySQL连接器API的Jetty 9.2(嵌入式),我对如何设置它感到困惑。 目前,我在我的web.xml文件中有这个:

<webapp ...  JDBC Data Source jdbc/DataSource javax.sql.DataSource Container   

…这在我的jetty-env.xml中:

    jdbc/DataSource   jdbc:mysql://localhost:3306/DBName user pass     

…以及此代码初始化:

 Context envCtx = (Context) new InitialContext().lookup("java:comp/env"); DataSource datasource = (DataSource) envCtx.lookup("jdbc/DataSource"); 

当我尝试启动服务器时,我收到错误javax.naming.NameNotFoundException; remaining name 'jdbc/DataSource' javax.naming.NameNotFoundException; remaining name 'jdbc/DataSource' 。 我已经在代码初始化中尝试了很多不同的字符串变体,比如删除了InitialContext对象上的lookup调用,但我只是不断地使用不同的name值来获取相同错误的变体。

这两个xml文件都位于我的/WAR/WEB-INF目录中。 我看过很多以前的问题和教程,博客等,但我无处可去。

这是嵌入式Jetty特有的问题组合。

首先,配置和启动Web服务器的启动器代码在我实际启动Web服务器之前server.start()即在调用server.start()之前server.start()执行JNDI查找,因此JNDI配置在该阶段未初始化。

但即使进行此更改也不起作用,因为需要从与WebApp关联的线程调用envCtx.lookup("jdbc/DataSource") 。 因此,我将该代码移动到静态块,在第一次Web服务器请求请求数据库连接时调用该块。

最后,我为我的启动器代码结束了这样的事情:

 public static void main(String[] args) { Server server = new Server(); //Enable parsing of jndi-related parts of web.xml and jetty-env.xml ClassList classlist = ClassList.setServerDefault(server); classlist.addAfter( "org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration"); ... ... server.start(); 

JNDI查找不能由这个主线程进行,所以把它放在像servlet请求的init方法那样的地方,或者就像我做的那样,是servlet使用的静态数据库访问器类的同步方法,例如

 public class DatabaseUtils { private static DataSource datasource; private static synchronized Connection getDBConnection() throws SQLException { if (datasource == null) { initDataSource(); } return datasource.getConnection(); } public static void initDataSource() { try { datasource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/DataSource"); LOG.info("Database connection pool initalized successfully"); } catch (Exception e) { LOG.error("Error while initialising the database connection pool", e); } }