By Jeff Chilton
"Success is simple. Do what's right, the right way, at the right time."
-- Arnold H. Glasgow (American Psychologist)
When they start using the WebSphere Application Server, most developers who have worked in application server environments other than WebSphere usually struggle a bit when attempting to locate their JDBC DataSources. Although both the process and syntax are similar enough to appear quite familiar, they're just different enough to prevent success without a little minor tweaking from what works in other environments.
The Familiar Method
If you've done any work with JDBC DataSources in a Web application, you already understand the basic process: create an initial JNDI (Java Naming and Directory Interface) context, then use the context to perform a "lookup" to retrieve your DataSource. In Java code, this usually looks something like this (for simplicity's sake, the requisite try/catch block surrounding these statements has been removed):
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDataSource");
While this looks great, and conforms to the established conventions used by most Web application servers, in a WebSphere Application Server this code will invariably result in the dreaded javax.naming.NameNotFoundException. To correctly locate your DataSource, you have two options, the first of which is a little simpler, but will result in some harmless messages cluttering up your server log file.
The WebSphere-specific Initial Context Factory
According to most IBM documentation and articles, the first thing you need to do when establishing an initial context is to set up the environment. The conventional code suggested for this operation looks something like this:
InitialContext ctx = new InitialContext(env);
This works great, although I must admit, I'm not sure exactly what this buys you. I run a lot of open source code on WebSphere that was originally written for other environments; most such code does not contain this set-up process and it all seems to work fine as long as the DataSource name parameter is correct.
According to the WebSphere Application Server 5.1 Information Center at http://publib.boulder.ibm.com/infocenter/ws51help/index.jsp?topic=/com.ibm.Websphere.base.doc/info/aes/ae/rnam_example_prop1.html: