Search code examples
javastringjndi

simple string value by JNDI in Java


How can i set simple string value in configuration of tomcat and then read in java application?

context.xml

<ResourceLink name="global/test" global="testing" type="java.lang.String" />

server.xml

<Enviroment name="testing" value="myUser" type="java.lang.String"/>

web.xml in application

<resource-env-ref>
    <resource-env-ref-name>global/test</resource-env-ref-name>
    <resource-env-ref-type>java.lang.String</resource-env-ref-type>
</resource-env-ref>

in my java application

public String getValue(){
    return new JndiDataSourceLookup().getDataSource("global/test").toString();
}

When i Run tomcat, i see these errors...

org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'global/test'; nested exception is javax.naming.NameNotFoundException: Name [global/test] is not bound in this Context. Unable to find [global].
javax.naming.NameNotFoundException: Name [global/test] is not bound in this Context. Unable to find [global].

Solution

  • In your web.xml use,

    <env-entry>
    <description>Sample env entry</description>
    <env-entry-name>isConnected</env-entry-name>
    <env-entry-type>java.lang.Boolean</env-entry-type><!--order matters -->
    <env-entry-value>true</env-entry-value>
    </env-entry>
    

    In code,

    try {
     Context initCxt =  new InitialContext();
     Boolean isConn =  (Boolean)initCxt.lookup("java:comp/env/isConnected");
     System.out.println(isConn.toString());
     // one could use relative names into the sub-context
     Context envContext = (Context) initCxt.lookup("java:comp/env");
     Boolean isConn2 = (Boolean)envContext.lookup("isConnected");
     System.out.println(isConn2.toString());
    } catch (NamingException e) {
     e.printStackTrace();
    }
    

    Have a look here Naming service tutorial to get a good understanding of InitialContext and JNDI.