问题
I am new to setting up JNDI resources and setting up JNDI resources in Tomcat.
I inherited a servlet application. It runs on a test server via WebLogic. The servlet application accesses its database resource in the following way:
ctx = new InitialContext();
ds = (javax.sql.DataSource)ctx.lookup("myDataBaseName");
conn = ds.getConnection();
When I tried that in a test JSP it doesn't work. I get
javax.naming.NameNotFoundException: Name myDataBaseName is not bound in this Context
However I was able to make the test JSP work if I altered the test JSP code thus:
ctx = new InitialContext();
Context envContext = (Context)ctx.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("myDataBaseName");
conn = ds.getConnection();
I have this entry in TOMCAT_HOME/conf/context.html ( I'm just using it as a dev environment on my box )
<Resource name="myDataBaseName"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@blahblahblah:1521:database3"
username="joeuser"
password="password"
maxActive="20"
maxIdle="30"
maxWait="-1"/>
</Context>
And I have this in my TOMCAT_HOME/conf/web.xml:
<resource-ref>
<res-ref-name>myDataBaseName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I read about 10 stackoverflow pages on related problems, but I am not familiar enough with setting up JNDI resources to abstract those solutions to my problem.
How can I change the way I have Tomcat 7 set up to allow the existing servlet application to access its database as "myDatabaseName"? I don't have the option of altering the code in the servlet application or altering the way WebLogic is set up on the test server.
I need to alter the way my copy of Tomcat 7 is set up on my computer ( for a dev environment ) to allow the servlet application to access its database in the style of the first chunk of quoted code at the top of this post.
回答1:
I see 2 possibilities here:
Implement a InitialContextFactory
and make it available to tomcat (via system property), so that new InitialContext()
gives you a context the lookup would work on.
or
Bind the data source to another place in the JNDI, which actually works although it is neither recommended nor documented (tomcat FM states the tree being read-only which only seems to apply to the subtree java:/comp/env):
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/myDataBaseName");
ctx.bind("myDataBaseName", ds);
回答2:
With the configuration that you provided you should be able to do the following:
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:/comp/env/myDataBaseName");
conn = ds.getConnection();
来源:https://stackoverflow.com/questions/6654132/how-to-set-up-a-resource-in-tomcat-7-so-that-i-dont-need-to-use-java-comp-e