On Wed, 07 Jul 2004 20:12:02 +0200, Bryan Hunt <[EMAIL PROTECTED]> wrote:

And it works fine, but really what I am trying to get here is the value of using Constants in
both my Actions and my ( JSTL based ) jsp's.

You need to have all your Constants in a Map that is in application scope. Kris Schneider posted this great piece of code to add to your Constants file to return all your constants as a Map. At app start up I have a servlet that does several things, one of which call the properties method to put all the stuff in a Map and then you can just put that in scope:



//in some servlet at startup: ServletContext context = contextEvent.getServletContext(); context.setAttribute("CONSTANTS", UIConstants.getConstantsMap());


(Below you don't need to do like I have. I had other reasons to do it this way at the time. But just provide the getConstantFieldsAsMap() method )


//example class: UIConstants

private static Map constantsMap;
static {
    constantsMap = getConstantFieldsAsMap(UIConstants.class);
}

public static Map getConstantsMap() {
    return constantsMap;
}

//all your constants:
public final static String WHATEVER = "whatever";

//this does the work.. thanks Kris
private static Map getConstantFieldsAsMap(Class cls) {
Map propMap = null;
try {
Field[] allFields = cls.getDeclaredFields();
int numFields = allFields.length;
propMap = new HashMap(numFields);
for(int i = 0; i < numFields; i++) {
Field f = allFields[i];
int mods = f.getModifiers();
if(Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
String name = f.getName();
Object value = f.get(null);
log.debug("Putting name = " + name + " and value=" + value + " into propMap");
propMap.put(name, value);
}
}
} catch(IllegalAccessException ie) {
log.error("Problem loading constantFieldsAsMap " + ie);
}
return Collections.unmodifiableMap(propMap);
}


//end class


Now in JSP you can just do:

<c:out value="${CONSTANTS.WHATEVER)"/>

--
Rick

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to