How to configure <Resource> in Tomcat 7 so that I do not need to use "java: / comp / env" in the code?
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 through WebLogic. The servlet application accesses the database resource as follows:
ctx = new InitialContext(); ds = (javax.sql.DataSource)ctx.lookup("myDataBaseName"); conn = ds.getConnection(); When I tried this in a test JSP, it does not work. I get
javax.naming.NameNotFoundException: Name myDataBaseName is not bound in this Context However, I managed to make the JSP test run if I changed the test JSP code this way:
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 just use it as a dev environment in 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 have read about 10 stackoverflow pages on related issues, but I am not good enough at configuring JNDI resources to distract these solutions from my problem.
How can I change the way Tomcat 7 is installed so that an existing servlet application can access its database as "myDatabaseName"? I have no way to change the code in the servlet application or to change the way WebLogic is created on the test server.
I need to change the way my copy of Tomcat 7 is configured on my computer (for the dev environment) so that the servlet application can access its database in the style of the first piece of quoted code at the top of this message.
With the configuration you provided, you can do the following:
ctx = new InitialContext(); ds = (DataSource)ctx.lookup("java:/comp/env/myDataBaseName"); conn = ds.getConnection(); Here I see two possibilities:
InitialContextFactory and make it available to tomcat (via the system property) so that new InitialContext() provides you with the context the search will work with.
or
Bind the data source to another place in JNDI that actually works, although it is not recommended and not documented (tomcat FM indicates that the tree is read-only, which seems to apply only to the java subtree: / comp / env):
Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:/comp/env/myDataBaseName"); ctx.bind("myDataBaseName", ds);