Java Static Constants in JSP and JSF ELBy Roger Keays, 17 July 2012, 6:56 AM |
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.
@ManagedBean
@ApplicationScoped
@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 ELJava 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:
${app.manager_role}
e.g.
<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.
![]() |
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, science, travel and surfing. You can follow Roger on Twitter and Google+. |
| « Nested Anonymous ui:insert Ignored in ui:define (Facelets) | Back to Blog | JSF Composite Components Where You Want Them » |