Access Java Static Methods and Constants from EL |
Java EL 3.0 provides a way to access static variables and static methods from JSF or JSP, but it's a bit nasty, requiring you to import the packages into your EL Context. I'm lazy and have been using this hack since 2012, so I'm just going to keep doing it for EL 3.0. The hack I'm using makes static methods and 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 accessors for static constants */ String root_dir = ROOT_DIR; String uploads_dir = UPLOADS_DIR; String image_dir = IMAGE_DIR; String manager_role = MANAGER_ROLE; /* EL accessors for static methods */ public long ctime() { return System.currentTimeMillis(); } }Access Java Static Methods and Constants from 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 statics via EL is:
${app.manager_role}
or
${app.ctime()}
As an added bonus, your IDE should be able to refactor your templates easily if you decide to change the variable names.
Alternatively, you could declare all your static methods in faces-config.xml but that's too much work for me, and you lose type safety and refactoring support.
Roger Keays is an artist, an engineer, and a student of life. He has no fixed address and has left footprints on 40-something different countries around the world. Roger is addicted to surfing. His other interests are music, psychology, languages, the proper use of semicolons, and finding good food. |