JNDI InitialContext problem

K

Kyle

In an example source file (AddressBook), I found the following codes:

InitialContext initialContext = new InitialContext ();
Context envContext = (Context) initialContext.lookup ("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup ("jdbc/Public");

I know it is using JNDI. But since the InitialContext is instantiated with
no parameter, the second statement seems strange to me. What does it mean by
"java:comp/env"? is it a standard Name? And the same for jdbc/Public?
BTW, Public is a name of a database.

I did not find any document on "java:comp/env"?

Thanks in advance
Kyle
 
J

Juha Laiho

Kyle said:
In an example source file (AddressBook), I found the following codes:

InitialContext initialContext = new InitialContext ();
Context envContext = (Context) initialContext.lookup ("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup ("jdbc/Public");

I know it is using JNDI. But since the InitialContext is instantiated
with no parameter, the second statement seems strange to me.

The JNDI implementation you use has some default context to which it
binds if the initial context is not specified.
What does it mean by "java:comp/env"? is it a standard Name? And the
same for jdbc/Public? BTW, Public is a name of a database.
I did not find any document on "java:comp/env"?

java:comp/env is one of the normal starting points for JNDI namespaces,
though I don't know where these are documented.

jdbc is a common subtree within java:comp/env, used to contain references
to database resources. Thus, the full path to your database resource is
java:comp/env/jdbc/Public. The common way is to use the three levels you
listed above; an InitialContext, the needed subcontextx (here envContext),
and then the actual resource (here the dataSource).

It is possible, however, to directly look up the database resource from
the InitialContext with just

InitialContext initialContext = new InitialContext ();
DataSource dataSource = (DataSource) initialContext.lookup ("java:comp/env/jdbc/Public");

.... and I don't know the justification for using the envContext as the
middle layer -- that's just the way it seems to be done everywhere.
 
K

Kyle

Thanks, Juha.
Your reply is of great help.
In addition, I found a context.xml file where the jdbc/Public resource is
defined. This justifies the jdbc/Public lookup.
Kyle
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top