2.3. Using Constants on JSPs
Problem
Without resorting to scriptlets, you want to use application
constants—
public static fields
defined in Java classes—on a JSP page.
Solution
Use the bind tag provided by the Jakarta Taglibs
unstandard
tag library to create a JSTL variable containing the value of
the constant field:
<%@ taglib uri="http://jakarta.apache.org/taglibs/unstandard-1.0" prefix="un" %>
<un:bind var="constantValue"
type="com.foo.MyClass"
field="SOME_CONSTANT"/>
<bean:write name="constantValue"/>Discussion
A lot of teams put hard work into avoiding hard-coded String literals
in their Java classes by using public
static fields (constants). Unfortunately, neither
Struts nor JSP provide a means to access these constants from a JSP
page without resorting to JSP scriptlet like the following:
<%= com.foo.MyClass.SOME_CONSTANT %>
However, many development teams ban, or at least frown on scriptlet use on JSP pages.
Warning
Scriptlets (<% . . . %>) and runtime
expressions (<%= . . . %>) place Java code
directly onto a JSP page. They are not inherently evil, but they can
lead your development down a slippery slope by turning your JSP pages
into a tangled brittle mass of intermixed HTML, JSP, and Java code.
Find solutions that don't require you to use
scriptlets. You'll find—particularly with the
introduction of JSTL—that you can always find a way around the
dreaded scriptlet.
The Solution provides a way around this quandary through the use of a
custom JSP tag, the
un:bind tag. This tag ...