2014-10-06 99 views
3

我正在使用标准的MySQL连接器API的Jetty 9.2(嵌入式),我很困惑这应该如何设置。目前,我有这个在我的的web.xml文件JNDI查找失败与Jetty的JDBC连接池与MySQL?

<webapp ... 

    <resource-ref> 
     <description>JDBC Data Source</description> 
     <res-ref-name>jdbc/DataSource</res-ref-name> 
     <res-type>javax.sql.DataSource</res-type> 
     <res-auth>Container</res-auth> 
    </resource-ref> 
</webapp> 

......这在我的码头-env.xml:

<Configure class="org.eclipse.jetty.webapp.WebAppContext"> 

    <New id="DatabaseConnector" class="org.eclipse.jetty.plus.jndi.Resource"> 
     <Arg></Arg> 
     <Arg>jdbc/DataSource</Arg> 
     <Arg> 
      <New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"> 
       <Set name="Url">jdbc:mysql://localhost:3306/DBName</Set> 
       <Set name="User">user</Set> 
       <Set name="Password">pass</Set> 
      </New> 
     </Arg> 
    </New> 

</Configure> 

......这码初始化:

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

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

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

+0

你可以发布你的Jetty Embedded实例的WebAppContext.setConfiguration()代码吗? – 2014-10-06 14:52:44

+0

我收到了我正在寻找其他地方的答案,我将发布一个总结解决方案的答案。 – RTF 2014-10-06 19:00:32

回答

1

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

首先,我配置和启动Web服务器的启动程序代码是在我实际启动Web服务器之前(即在调用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查找无法通过这个主线进行,所以把它放在什么地方像一个的init方法servlet请求,或者像我一样,一个静态数据库访问器类的同步方法,被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); 
     } 
    }