Skip to content

JSTL accessing Constants from a Java Constants class

This class is to get around a minor inconvenience. JSTL 1.1 does not support referencing constants defined in Java classes/interfaces. Thus to provide the ability to reference the constant within JSTL e.g. ${Constants.DISPLAY_MODE}, this class uses reflection to read the Constants interface and initializes
a application scoped hashmap. Thus JSTL tags within the application can write {WebConstants.Constants.DISPLAY_MODE}. This invokes the get method that looks up the statically defined map to return the appropriate value

The lookup will throw an IllegalArgumentExceptionin case of an invalid key passed in

package com.reverttoconsole;

public interface Constants {
    public static final int MODE_READONLY = 0;
    public static final int MODE_READWRITE = 1;

}
package com.reverttoconsole

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;

public class WebConstants extends HashMap {
    private static final Logger logger = Logger.getLogger("com.reverttoconsole.WebConstants");? ? ?
private static Map reflectedConstants;
 //This member is used to indirectly reference the application's Constants interface
  public static final WebConstants Constants = new WebConstants();

// this static initializer reads the Constants and initializes the map
 static {
 reflectedConstants = new HashMap();
 Field[] fields = Constants.class.getFields(); // the Constants class.
 int i = 0;
 try {
  for (i = 0; i < fields.length; i++) {
 reflectedConstants.put(fields[i].getName(), fields[i].get(null));
  }
  } catch (IllegalAccessException ex) {
 logger.debug("Exception accessing field: " + fields[i].getName());

  }
 }

 public Object get(Object key) {
  // we need to use reflection to inspect
  Object value = reflectedConstants.get(key);
 if (value == null) {
throw new IllegalArgumentException("[" + key + "] " +
 "No such constant defined in class Constants");
 }
  return value;
}
}

the sample jsp file

<!--page import="com.reverttoconsole.WebConstants-->
<set var="Constants" value="&amp;amp;&amp;lt;%=WebConstants.Constants%"></set>
...
<if test="${command.mode == Constants.MODE_READONLY}"></if></pre>
Writing a Tag library for the same would be even better
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*