我正在使用Websphere Portal 7.0并创建一个带RAD 8.0的portlet。我的portlet正在尝试建立到远程服务器的db2连接。我在本地编写了一个java程序来对服务器进行基本的JDBC连接,并从表中获取记录。代码工作正常但是,当我将代码添加到我的portlet以及db2jcc4.jar时,连接不起作用。我使用的基本:
Connection connection = DriverManager.getConnection("jdbc:db2://server:port/db:user=user;password=pw;");
我认为使用Websphere数据源是正确的方法。我知道数据源的JNDI名称,但是我没有找到关于如何建立连接的明确例子。几个示例使用DataSource类(我键入这个,这似乎不是来自一个本机java包,所以我在这里使用什么导入))加上一个上下文。我遇到过如下代码:
Context ctx = new InitialContext();
ctx.lookup("jdbc/xxxx");
…
有人可以为我打破这一切吗?
编辑1
我已经按照列出的答案更新了我的代码。我真的认为我越来越近了这是我的getConnection()方法:
private Connection getConnection() throws SQLException {
javax.naming.InitialContext ctx = null;
javax.sql.DataSource ds = null;
System.out.println("Attempting connection..." + DateUtil.now() );
try {
ctx = new javax.naming.InitialContext();
ds = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/db");
connection = ds.getConnection();
} catch (NamingException e) {
System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!");
e.printStackTrace();
}
System.out.println("connection: " + connection.getClass().getName() + " at " + DateUtil.now());
return connection;
}
我的整个web.xml文件如下所示:
PeformanceAppraisalStatus
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
Datasource connection to Db
jdbc/db
javax.sql.DataSource
Container
Shareable
我看到一个错误,描述了你们告诉我的东西Websphere应该提示我做,但不是:
SRVE0169I: Loading Web Module: PeformanceAppraisalStatus.
[8/23/11 18:08:02:166 CDT] 00000009 InjectionProc E CWNEN0044E: A resource reference binding could not be found for the jdbc/db resource reference, defined for the PeformanceAppraisalStatus component.
[8/23/11 18:08:02:169 CDT] 00000009 InjectionEngi E CWNEN0011E: The injection engine failed to process bindings for the metadata.
是的,我知道在整个应用程序中,我已经将性能拼出来了。
解
我非常亲密这是丢失的位,使它都落在了位置:
web.xml:
Datasource connection to db
jdbc/db
javax.sql.DataSource
Container
Shareable
jdbc/db
ibm-web-bnd.xml:
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
version="1.0">
看来ibm-web-bnd.xml文件处理项目资源名称和websphere中的数据源之间的绑定。一旦我添加了一行:
Websphere Portal似乎安抚了。我的代码正在工作并连接到数据库。