Search code examples
javatomcatservletsjakarta-mailjndi

is it possible to set the value and access in context.xml in tomcat7 like JNDI?


I would like to set some values in context.xml file and access the same from my Servlet like we access in JNDI:

mail.smtp.host=smtp.gmail.com
mail.smtp.port=465

Can I do this?


Solution

  • Yes its absolutely possible

    <Environment name="testEnvEntry" value="Got It"
             type="java.lang.String" override="false"/>
    

    Then access this like:

    Object lookedUp = null;
    try {
        InitialContext initialContext = new InitialContext();
        lookedUp = initialContext.lookup("java:/comp/env/testEnvEntry");
    } catch (NamingException e) {
        e.printStackTrace();
    }
    

    It is similar to how you would add <env-entry> in your web.xml.

    You can read the official documentation of Environment here