问题
How does a look-up like :
Context envContext = (Context)initContext.lookup("java:comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MyDatasource");
proceed ?
I mean to say how is the name MyDataSource
searched and in the end what is returned ?
There are two entries added to connect to the database. One in the WEB-INF/web.xml
which is :
<resource-ref>
<description>my connection</description>
<res-ref-name>jdbc/MyDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
and the other added in the META-INF/context.xml
which is :
<Resource name="jdbc/MyDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/My Database;create=true"
username="me" password="me"
maxActive="20" maxIdle="10" maxWait="-1" />
How does these 2 entries help in the look up ?
What is looked first : web.xml
or context.xml
?
Please explain the whole process in the look up.
回答1:
Resources are located in this order of preference: web.xml
(via <resource-ref>
elements, context.xml
, server.xml
(via <GlobalNamingResources>
). Note that resource defined in your <Context>
do not actually need to have corresponding <resource-ref>
elements in your web.xml
. See the Tomcat documentation regarding JNDI resources: http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html
回答2:
The following are the steps to do a lookup:
STEP 1:
Context context = new InitialContext():
The initial context is a reference to the JNDI lookup service. It is like the entry into the JNDI virtual directory tree.
STEP 2:
Object o = context.lookup("mejb"):
Here in the lookup we need to give the name of the bean whatever that is deployed in the server, to get a reference to the home interface of that bean.We then get the object of type java.lang.Object we need to cast this object to the Home interface of whichever bean we did a lookup on.
STEP 3:
Home home = (Home) PortableRemoteObject.narrow(o,Home.class):
We actually need to cast the object to the type that we think it is type of. However, since this is RMI over IIOP it seems we need to use the PortableRemoteObject.narrow method this it seems filters the object type to the actual object type and checks for errors.
来源:https://stackoverflow.com/questions/11553889/what-are-steps-followed-in-the-look-up-what-is-looked-first-web-xml-or-context