【发布时间】:2014-12-22 15:59:58
【问题描述】:
我有一个用于构建报表的应用程序,现在我需要将此应用程序移动到 Web 环境。
为此,我使用的是 Tomcat 8.0.15 和 Oracle Database 11g 企业版。
在我的 TOMCAT_HOME\conf\server.xml 我有以下代码:
<Resource auth="Container"
driverClassName="oracle.jdbc.OracleDriver"
maxIdle="10"
maxTotal="20"
maxWaitMillis="-1"
name="jdbc/reportDataSource"
username="some_username"
password="some_pass"
type="javax.sql.DataSource"
url="jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = some.host)(PORT = some.port)))(CONNECT_DATA =(SID = SOME_SID)(SERVICE_NAME = SOME_SERVICE)))"/>
因此在我的 PROJECT_HOME\WebContent\WEB-INF\web.xml 我有以下内容:
<resource-ref>
<description>Oracle Datasource definition</description>
<res-ref-name>jdbc/reportDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
最后,在我的代码中,我有一个 Java 类,其中包含以下内容:
private void init() throws NamingException, SQLException {
try {
InitialContext initialContext = new InitialContext(); // JNDI initial context
Context eventContext = (Context) initialContext.lookup("java:comp/env/jdbc/reportDataSource"); // Event context
dataSource = (DataSource) eventContext.lookup("jdbc/reportDataSource"); // JNDI lookup
databaseConnection = dataSource.getConnection(); // database connection through data source
} catch (SQLException se) {
throw new SQLException("Connection object was not created. Rejected by host or not found.");
} catch (NamingException ne) {
throw new NamingException(ne.getMessage());
}
}
最后在我的项目根目录中,我有以下测试设置:
@Before
public void setUp() throws Exception {
dbConnectorManager = new DatabaseConnectorManager();
assertNotNull(dbConnectorManager);
}
当我调用 DatabaseConnectorManager() 时,它会调用此问题中显示的 init() 方法。但是,当我执行测试时,出现以下与行相关的错误:
entContext eventContext = (Context) initialContext.lookup("java:comp/env/jdbc/reportDataSource"); // Event context
因此,由于以下错误,无法设置 JNDI:
javax.naming.NamingException: 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
您能否告知我是否可以创建这些 JUnit 测试来测试连接性,或者我是否只能通过 servlet 进行测试?
我的配置有什么问题吗?
更新
我进行了指定的更改,但现在出现以下错误:
javax.naming.NamingException: Name [jdbc/reportDataSource] is not bound in this Context. Unable to find [jdbc].
我的数据源现在如下所示:
InitialContext initialContext = new InitialContext(); // JNDI initial context
Context eventContext = (Context) initialContext.lookup("java:comp/env"); // Event context
dataSource = (DataSource) eventContext.lookup("jdbc/reportDataSource"); // JNDI lookup
databaseConnection = dataSource.getConnection(); // database connection through data source
【问题讨论】:
-
不确定这是否有帮助,但不妨看看这个问题:stackoverflow.com/questions/744389/…
标签: java oracle tomcat jdbc junit4