Glassfish JNDI settings

Recently we had the need to add some configurable settings (such as user credentials) in a Java EE 7 application running on Glassfish 4.0.

An example method to read the values might look like this:

    private String getUserProperty(String property) {

        String result = "";
        Properties properties;
        try {
            InitialContext context = new InitialContext();
            properties = (Properties) context.lookup("jndi/userinfo");
            result = properties.getProperty(property);
        } catch (NamingException e) {
        return result;

Setting the values via the Glassfish console is achieved via Resources -> JNDI -> Custom Resources.  Then clicking the New button will allow the new JNDI resource to be added.  Here we are using a java.util.Properties type so that we can add name/value pairs as needed below.

Then, for example, to get the username, we might do this:

String username = getUserProperty("username");

The code should be cleaned up a bit (handle exception, add constants, etc.) but hopefully it illustrates the point.


Post a Comment

Popular posts from this blog

ClassCastException: JAXB

Android and JavaFX

Glassfish Informix JDBC