Tomcat嵌入式:尝试获取数据源时的NoinitialContextException



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

我可能缺少一些明显的东西,但是关于嵌入的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();

Web应用程序本身就是这样:

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

抛出的例外是:

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)

[line userbean.java:77是上面的ctx.lookup()

我对如何进步感到不满意。

显然我只需要tomcat.enablenaming(),默认情况下不启用。

最新更新