我有一个这样的示例代码:
ConnectionPool.dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/murach");
并且在webapp/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/murach"
auth="Container"
type="javax.sql.DataSource"
username="root"
--- Rest of the text ---/>
</Context>
当我将此 Web 应用程序部署到 Tomcat 时,数据库连接正常,但是当我使用 Jetty 插件尝试使用 Jetty 时:jetty:run-war
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.1.v20140609</version>
<configuration>
<scanIntervalSeconds>2</scanIntervalSeconds>
<httpConnector>
<port>8082</port>
</httpConnector>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
我得到:
javax.naming.NameNotFoundException; remaining name 'jdbc/murach'
我怎样才能使它也与 jetty 一起工作?
我也试过添加
<resource-ref>
<description>murach</description>
<res-ref-name>jdbc/murach</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
到 web.xml,但现在我得到:
java.lang.IllegalStateException: Nothing to bind for name javax.sql.DataSource/default
最佳答案
Jetty 应配置为使用 JNDI 并将 JNDI 资源部署到其中。
尝试添加到maven插件配置:
<configuration>
<!-- ... -->
<jettyEnvXml>src/main/dev-path-to-jetty-env-xml/jetty-env.xml</jettyEnvXml>
<webXml>src/main/dev-path-to-web-xml/web.xml</webXml>
</configuration>
文件 jetty-env.xml
看起来像(仅作为示例;使用 bonecp 数据源):
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<New id="murachDataSource" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/murach</Arg>
<Arg>
<New class="com.jolbox.bonecp.BoneCPDataSource">
<Set name="driverClass">org.h2.Driver</Set>
<Set name="jdbcUrl">jdbc:h2:~/murach/test</Set>
<Set name="username">sa</Set>
<Set name="password"/>
<Set name="partitionCount">4</Set>
<Set name="minConnectionsPerPartition">5</Set>
<Set name="acquireIncrement">5</Set>
<Set name="closeConnectionWatch">false</Set>
</New>
</Arg>
</New>
</Configure>
文件 web.xml
应包含行:
<resource-ref>
<description>My DataSource Reference</description>
<res-ref-name>jdbc/murach</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
关于Jetty 中的 javax.naming.NameNotFoundException 但 Tomcat 中没有。怎么解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31489484/