Tomcat嵌入式:尝试获取DataSource时的NoInitialContextException

Gar*_*y B 5 java tomcat jdbc

我有一个JSF Web应用程序,我想使用嵌入式tomcat运行.它到目前为止[包括JDBCRealm,在以下代码片段的context.xml中指定],除了登录后我的代码无法实际获取源中指定的连接资源,抛出NoInitialContextException.

我可能错过了一些明显的东西,但是关于tomcat嵌入的似乎很少有流量.[Tomcat7.0.47,JDK7].

由于其他问题这个网站上这个网站,我已经尝试了多种变体上添加一个初始环境,但我一直无法弄清楚,如果这真的是我的问题,还是我只是还没有找到合适的这个tomcat服务器的咒语.

Tomcat启动代码:

tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir(".");
Context ctx = tomcat.addWebapp("/" + appname, appname);
// The login realm specified in this XML file is a JDBC realm, and the server correctly logs users in, so I believe this is parsed.
ctx.setConfigFile(new URL("file:///home/chunky/src/aqmt/AQMTEmbed/webapps/AQMTWeb/META-INF/context.xml"));

ContextResource resource = new ContextResource();
resource.setName("jdbc/aqmtwebdb");
resource.setAuth("Container");
resource.setType("javax.sql.DataSource");
resource.setScope("Sharable");
resource.setProperty("driverClassName", "com.mysql.jdbc.Driver");
resource.setProperty("url", "jdbc:mysql://localhost:3306/aqmtweb?autoreconnect=true");
resource.setProperty("username", "username");
resource.setProperty("password", "password");
ctx.getNamingResources().addResource(resource);

tomcat.start();
Run Code Online (Sandbox Code Playgroud)

在Web应用程序本身是这样的:

InitialContext ctx = new InitialContext();
// This line here throws the exception:
DataSource webds = (DataSource)ctx.lookup("java:/comp/env/jdbc/aqmtwebdb");
Run Code Online (Sandbox Code Playgroud)

抛出的异常是:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)
    at org.rand.aqmt.UserBean.<init>(UserBean.java:77)
Run Code Online (Sandbox Code Playgroud)

[其中UserBean.java:77行是上面的ctx.lookup()]

我对如何进步感到很茫然.

Gar*_*y B 13

显然我只需要Tomcat.enableNaming(),默认情况下不启用.