Search code examples
jakarta-eetomcattomcat7jndi

Datasource fails when app deployed inside a folder in webapps in tomcat


I registered a domain www.mywebapp.com and pointed the name servers to my tomcat hosting. So when I give www.mywebapp.com is given , it hits the

tomcat/webapps/mywebapp.com

and pages get loaded with no issues.So that much part is correct.

But I am not able to establish DB connection ( using JNDI datasource ) for my application,because When I call -

DBConnection.ds = (DataSource)ctx.lookup("java:comp/env/jdbc/atfdb"); 

It says

DB Connection NamingException error-->Name atfdb is not bound in this Context.

Note:

I am using tomcat7.

The DB connection is established if I deploy the app directly under tomcat/webapps folder,the problem comes only when I deploy it inside webapps/mywebapp.com.

Is there any special case for JNDI lookup if we deploy the war file inside webapps/mywebapp.com ?

Below are my configurations

server.xml  inside tomcat/conf/server.xml
-------------------------------------------

<Host appBase="webapps/mywebapp.com" name="mywebapp.com" unpackWARs="true" autoDeploy="true">
      <Alias>www.mywebapp.com</Alias>
      <Context path="" docBase="ROOT" debug="0" reloadable="true"/>
      <Logger className="org.apache.catalina.logger.FileLogger" prefix="mywebapp.com"   suffix=".txt" timestamp="true"/>
      </Host>


context.xml in which I am configuring my datasource.


context.xml   inside webapps/mywebapp.com/META-INF
--------------------------------------------------

<Context>

  <Resource name="jdbc/atfdb" auth="Container" type="javax.sql.DataSource"
               removeAbandoned="true" maxActive="100" maxIdle="30" maxWait="10000"
               removeAbandonedTimeout="30" username="spadmin" password="password" 
               driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/socialdb?autoReconnect=true"/>

</Context>

Solution

  • I would add a resource reference into your web.xml:

    <resource-ref>
        <description>atfdb description</description>
        <res-ref-name>jdbc/atfdb</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    

    This is what is expected as per Java EE standard, so the fact that it works when you use the other folder could just be a fluke...