We Solve Problems

Java Static Constants in JSP and JSF EL

By , 17 July 2012

Java Static Constants in JSP and JSF EL

For the moment, Java EL doesn't provide any way to access static variables and static methods from JSF or JSP. Here's a hack I'm using which makes static constants available via normal managed beans. Note, I'm using Lombok annotations to generate the getters and setters automatically.

@Getter @Setter 
public class App {
    /* global compile-time constants */
    public static final String ROOT_DIR = "/var/local";
    public static final String UPLOADS_DIR = "/var/local/uploads";
    public static final String IMAGE_DIR = "/var/local/images";
    public static final String MANAGER_ROLE = "manager";

    /* EL constants */
    String root_dir = ROOT_DIR;
    String uploads_dir = UPLOADS_DIR;
    String image_dir = IMAGE_DIR;
    String manager_role = MANAGER_ROLE;
Java Static Constants in JSP and JSF EL

Java identifiers are case sensitive so there is no namespace problem with the static and non-static properties. Now, all we need to do to access the constants via EL is:



 <c:if test="${user.role eq app.manager_role}"/>

As an added bonus, your IDE should be able to refactor your templates easily if you decide to change the variable names.


About Roger Keays

Roger is an active member of the JSF 2 Expert Group and is happy to be a contributor to the Java Community. He has been writing software since the age of 8 and his other interests include languages, psychology, travel and running.

Add a comment

Please visit http://www.NinthAvenue.com.au/java-static-constants-in-jsp-and-jsf-el to add your comments.

Comment posted by: kenneth centurion, 6 months ago

you can also display values from the facescontext sesionmap like this:

<p:outputLabel value="Last Logged In:[#{sessionScope.lastLoginDate}]"/>


and in your bean you can put a value in the session map like this:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("lastLoginDate",new Date());

Comment posted by: , 3 years ago

That works too, but I actually like how the application scoped bean creates a mini namespace for my constants.

Some people also use the "map hack". i.e. override the get() method of a Map.

Comment posted by: Tom Asel, 3 years ago

 Nice one :-)

Another approach is to have a custom ELResolver enabling you to use custom implicit objects.

E.g. SomeClass.MY_CONSTANT could be accessed via #{myConstant} . I prefer this one over application scoped beans for my projects.

Join The Mailing List

Subscribe to our mailing list for the latest news and announcements.

Follow Ninth Avenue

Website Updates