How do you reference an constants with EL on a JSP page?
I have an interface Addresses with a constant named URL. I know I can reference it with a scriplet by going: <%=Addresses.URL%>, but how do I do this using EL?
EL 3.0 or newer
If you're already on Java EE 7 / EL 3.0, then the #page import will also import class constants in EL scope.
<%# page import="com.example.YourConstants" %>
This will under the covers be imported via ImportHandler#importClass() and be available as ${YourConstants.FOO}.
Note that all java.lang.* classes are already implicitly imported and available like so ${Boolean.TRUE} and ${Integer.MAX_VALUE}. This only requires a more recent Java EE 7 container server as early versions had bugs in this. E.g. GlassFish 4.0 and Tomcat 8.0.0-1x fails, but GlassFish 4.1+ and Tomcat 8.0.2x+ works. And you need to make absolutely sure that your web.xml is declared conform the latest servlet version supported by the server. Thus with a web.xml which is declared conform Servlet 2.5 or older, none of the Servlet 3.0+ features will work.
Also note that this facility is only available in JSP and not in Facelets. In case of JSF+Facelets, your best bet is using OmniFaces <o:importConstants> as below:
<o:importConstants type="com.example.YourConstants" />
Or adding an EL context listener which calls ImportHandler#importClass() as below:
#ManagedBean(eager=true)
#ApplicationScoped
public class Config {
#PostConstruct
public void init() {
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() {
#Override
public void contextCreated(ELContextEvent event) {
event.getELContext().getImportHandler().importClass("com.example.YourConstants");
}
});
}
}
EL 2.2 or older
This is not possible in EL 2.2 and older. There are several alternatives:
Put them in a Map<String, Object> which you put in the application scope. In EL, map values are accessible the usual Javabean way by ${map.key} or ${map['key.with.dots']}.
Use <un:useConstants> of the Unstandard taglib (maven2 repo here):
<%# taglib uri="http://jakarta.apache.org/taglibs/unstandard-1.0" prefix="un" %>
<un:useConstants className="com.example.YourConstants" var="constants" />
This way they are accessible the usual Javabean way by ${constants.FOO}.
Use Javaranch's CCC <ccc:constantsMap> as desribed somewhere at the bottom of this article.
<%# taglib uri="http://bibeault.org/tld/ccc" prefix="ccc" %>
<ccc:constantsMap className="com.example.YourConstants" var="constants" />
This way they are accessible the usual Javabean way by ${constants.FOO} as well.
If you're using JSF2, then you could use <o:importConstants> of OmniFaces.
<html ... xmlns:o="http://omnifaces.org/ui">
<o:importConstants type="com.example.YourConstants" />
This way they are accessible the usual Javabean way by #{YourConstants.FOO} as well.
Create a wrapper class which returns them through Javabean-style getter methods.
Create a custom EL resolver which first scans the presence of a constant and if absent, then delegate to the default resolver, otherwise returns the constant value instead.
The following does not apply to EL in general, but instead to SpEL (Spring EL) only (tested with 3.2.2.RELEASE on Tomcat 7).
I think it is worth mentioning it here in case someone searches for JSP and EL (but uses JSP with Spring).
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<spring:eval var="constant" expression="T(com.example.Constants).CONSTANT"/>
You usually place these kinds of constants in a Configuration object (which has getters and setters) in the servlet context, and access them with ${applicationScope.config.url}
You can't. It follows the Java Bean convention. So you must have a getter for it.
I'm defining a constant in my jsp right at the beginning:
<%final String URI = "http://www.example.com/";%>
I include the core taglib in my JSP:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Then, I make the constant available to EL by following statement:
<c:set var="URI" value="<%=URI%>"></c:set>
Now, I can use it later. Here an example, where the value is just written as HTML comment for debugging purposes:
<!-- ${URI} -->
With your constant class, you can just import your class and assign the constants to local variables. I know that my answer is a sort of quick hack, but the question also bumps up when one wants to define constants directly in the JSP.
I implemented like:
public interface Constants{
Integer PAGE_SIZE = 20;
}
-
public class JspConstants extends HashMap<String, String> {
public JspConstants() {
Class c = Constants.class;
Field[] fields = c.getDeclaredFields();
for(Field field : fields) {
int modifier = field.getModifiers();
if(Modifier.isPublic(modifier) && Modifier.isStatic(modifier) && Modifier.isFinal(modifier)) {
try {
Object o = field.get(null);
put(field.getName(), o != null ? o.toString() : null);
} catch(IllegalAccessException ignored) {
}
}
}
}
#Override
public String get(Object key) {
String result = super.get(key);
if(StringUtils.isEmpty(result)) {
throw new IllegalArgumentException("Check key! The key is wrong, no such constant!");
}
return result;
}
}
Next step put instance of this class into servlerContext
public class ApplicationInitializer implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("Constants", new JspConstants());
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
add listener to web.xml
<listener>
<listener-class>com.example.ApplicationInitializer</listener-class>
</listener>
access in jsp
${Constants.PAGE_SIZE}
Static properties aren't accessible in EL. The workaround I use is to create a non-static variable which assigns itself to the static value.
public final static String MANAGER_ROLE = 'manager';
public String manager_role = MANAGER_ROLE;
I use lombok to generate the getter and setter so that's pretty well it. Your EL looks like this:
${bean.manager_role}
Full code at https://rogerkeays.com/access-java-static-methods-and-constants-from-el
Yes, you can. You need a custom tag (if you can't find it somewhere else). I've done this:
package something;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.taglibs.standard.tag.el.core.ExpressionUtil;
/**
* Get all class constants (statics) and place into Map so they can be accessed
* from EL.
* #author Tim.sabin
*/
public class ConstMapTag extends TagSupport {
public static final long serialVersionUID = 0x2ed23c0f306L;
private String path = "";
private String var = "";
public void setPath (String path) throws JspException {
this.path = (String)ExpressionUtil.evalNotNull ("constMap", "path",
path, String.class, this, pageContext);
}
public void setVar (String var) throws JspException {
this.var = (String)ExpressionUtil.evalNotNull ("constMap", "var",
var, String.class, this, pageContext);
}
public int doStartTag () throws JspException {
// Use Reflection to look up the desired field.
try {
Class<?> clazz = null;
try {
clazz = Class.forName (path);
} catch (ClassNotFoundException ex) {
throw new JspException ("Class " + path + " not found.");
}
Field [] flds = clazz.getDeclaredFields ();
// Go through all the fields, and put static ones in a Map.
Map<String, Object> constMap = new TreeMap<String, Object> ();
for (int i = 0; i < flds.length; i++) {
// Check to see if this is public static final. If not, it's not a constant.
int mods = flds [i].getModifiers ();
if (!Modifier.isFinal (mods) || !Modifier.isStatic (mods) ||
!Modifier.isPublic (mods)) {
continue;
}
Object val = null;
try {
val = flds [i].get (null); // null for static fields.
} catch (Exception ex) {
System.out.println ("Problem getting value of " + flds [i].getName ());
continue;
}
// flds [i].get () automatically wraps primitives.
// Place the constant into the Map.
constMap.put (flds [i].getName (), val);
}
// Export the Map as a Page variable.
pageContext.setAttribute (var, constMap);
} catch (Exception ex) {
if (!(ex instanceof JspException)) {
throw new JspException ("Could not process constants from class " + path);
} else {
throw (JspException)ex;
}
}
return SKIP_BODY;
}
}
and the tag is called:
<yourLib:constMap path="path.to.your.constantClass" var="consts" />
All public static final variables will be put into a Map indexed by their Java name, so if
public static final int MY_FIFTEEN = 15;
then the tag will wrap this in an Integer and you can reference it in a JSP:
<c:if test="${consts['MY_FIFTEEN'] eq 15}">
and you don't have to write getters!
You can. Try in follow way
#{T(com.example.Addresses).URL}
Tested on TomCat 7 and java6
Even knowing its a little late, and even knowing this is a little hack - i used the following solution to achieve the desired result. If you are a lover of Java-Naming-Conventions, my advice is to stop reading here...
Having a class like this, defining Constants, grouped by empty classes to create kind of a hierarchy:
public class PERMISSION{
public static class PAGE{
public static final Long SEE = 1L;
public static final Long EDIT = 2L;
public static final Long DELETE = 4L;
...
}
}
can be used from within java as PERMISSION.PAGE.SEE to retrieve the value 1L
To achieve a simliar access-possibility from within EL-Expressions, I did this:
(If there is a coding-god - he hopefully might forgive me :D )
#Named(value="PERMISSION")
public class PERMISSION{
public static class PAGE{
public static final Long SEE = 1L;
public static final Long EDIT = 2L;
public static final Long DELETE = 4L;
...
//EL Wrapper
public Long getSEE(){
return PAGE.SEE;
}
public Long getEDIT(){
return PAGE.EDIT;
}
public Long getDELETE(){
return PAGE.DELETE;
}
}
//EL-Wrapper
public PAGE getPAGE() {
return new PAGE();
}
}
finally, the EL-Expression to access the very same Long becomes: #{PERMISSION.PAGE.SEE} - equality for Java and EL-Access. I know this is out of any convention, but it works perfectly fine.
#Bozho already provided a great answer
You usually place these kinds of constants in a Configuration object (which has getters and setters) in the servlet context, and access them with ${applicationScope.config.url}
However, I feel an example is needed so it brings a bit more clarity and spare someone's time
#Component
public Configuration implements ServletContextAware {
private String addressURL = Addresses.URL;
// Declare other properties if you need as also add corresponding
// getters and setters
public String getAddressURL() {
return addressURL;
}
public void setServletContext(ServletContext servletContext) {
servletContext.setAttribute("config", this);
}
}
There is a workaround that is not exactly what you want, but lets you active almost the same with touching scriptlets in a quite minimal way. You can use scriptlet to put value into a JSTL variable and use clean JSTL code later in the page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="com.whichever.namespace.Addresses" %>
<c:set var="ourUrl" value="<%=Addresses.URL%>"/>
<c:if test='${"http://www.google.com" eq ourUrl}'>
Google is our URL!
</c:if>
I have a jsp page. Page have a requested field as string.
<% String token = ""+request.getParameter(); %>
In this jsp page also has a test class.
<%!
public static String usetoken()
{
String testtoken = ""+token;
}
%>
This usetoken class can not solve the token string. How can I solve that ? I need to call a string inside a class which inside a jsp page.
Thanks,
Firstly, as you may know, a jsp will be compiled to a servlet. All scriptlet code will be "inserted" into service() method and all declarations will be inserted to servlet class. So, for your situation, we'll have something like this(simplified):
public class FooServlet extends HttpServlet {
public static String useToken() {
String testtoken = ""+ token;
return testtoken;
}
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String token = ""+ request.getParameter();
}
}
As you see, userToken() method can't know about 'token' local variable inside service() method.
Also, you can't access HttpServletRequest in your jsp declaration, because it's a parameter of service() method.
BUT
You can use JSTL for something like this. You can declare variable:
<c:set var="token" value="${requestScope.token}"/>
And access it anywhere in your jsp using expression language(EL):
${token}
If you don't know, writing scriptlets inside your jsp considered bad practice. You need to do business logic somewhere outside and provide view as jsp. So use JSTL, your custom tags and EL.
I want to use JSTL within JSP declaration. I have code like:
<%! void fetchData(String .., String ..){
//some code...
pageContext.setAttribute("test",valueForJSTL); // Wont work until I pass pageContext from calling scriptlet
//some code...
%><%
//use pageContext variable set above to user in JSP (c:out, wcf:getData etc)**
%><%
}%>
I wonder why is it not allowed to used scriptlet (line 5-7) within JSP declaration. Or is there any other way to handle this?
I am calling above function from a scriptlet and I want this method to do some manipulation, add a variable in pageContext/request and fetch the variable in JSTL to fetch the data from DB .
You can find complete file at:
http://wikisend.com/download/738986/MyView.jsp
The JSTL within declaration "fetchCatalogEntries" is not working.
This is because the generated code for the scriptlet <% %>goes in the service method which is like called again and over the same object using multiple request threads
Whereas <%!, goes into the global class space or simply to declare methods and variables global for a JSP page.
Hence in your scriptlet you can call the method say fetchData() or any other like you would inside a service() method like in a normal java class.
You can even declare a field as below and refer it as in the example below :
<%!
private final Logger logger = new Logger(this.getClass());
private UserService userService = null;
public void jspInit() {
userService = new UserService();
}
private String getUserStatus(String userID) {
return userServce.getUserStatus(userID);
}
%>
<%
String userID = request.getParameter("userid");
String userStatus = getUserStatus(userID);
%>
Finally I would recommend you to NOT use scriptlets and use JSTL tags and libraries like the core-tag-libs and many others, these will help you in the long term.
I have following library class:
public class LibClass{
public int get(int a, String b) {
....
return 12;
}
}
How to invoke following method on jsp?
I want to render 12 on jsp.
P.S.
I have restriction that I cannot use scriplets
You can do that using expression language. For ex
Assuming that you've a ${instance} in the scope
${instance.get(1,"test")}
There is another way. You can make a simple Bean which gets this value
public String getDATE(){
String Date = String.valueOf(new java.util.Date());
return Date;
}
and then call the above method with the following jsp tag
<jsp:useBean id="now" class="beans.PropertyBean" />
<jsp:getProperty name="now" property="DATE" />
you can use anything returned from the bean, In above snippet 'PropertyBean' is the name of my custom bean class. Hope this answers your question.
This question already has answers here:
How to reference constants in EL?
(12 answers)
Closed 6 years ago.
When trying to get an EL condition working I found that enum values are completely ignored. This seems to me contrary to the spec.
<c:out value='${com.foobar.data.BookingStatus.FAILED}' />
<c:out value='${BookingStatus.FAILED}' />
<c:out value='${com.foobar.data.BookingStatus.failed}' />
<c:out value='${BookingStatus.failed}' />
<c:if test="${empty BookingStatus.FAILED }">empty</c:if>
To my surprise these all evaluate to empty. Why is the Enum class not recognized?
This is happening in a current stable Tomcat instance.
Can this be a classpath issue? The Enum is used successfully in controller code but nowhere else in JSPs. It is supplied in a jar in the lib directory of the deployment.
UPDATE:
My intention is to compare a supplied Integer to an Enum's property like this:
<c:when test='${bookingInformation.bookingStatus eq BookingStatus.FAILED.code}'>
FOOBARFAIL
</c:when>
Unfortunately the value being checked can't be changed and will remain an Integer. The Enum looks as follow (simplified):
public enum BookingStatus {
COMPLETED(0), FAILED(1);
private final int code;
private BookingStatus(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
I want to avoid to hard code the Integer value of FAIL etc. and use the enum instead for the comparison.
That's because EL in its current version does not support accessing enums nor calling enum constants. This support is only available per EL 3.0.
It's unclear what your intent is, but it's good to know that you can compare enum properties as a String in EL. They are namely resolved as a String.
Assuming that you've a bean which look like this:
public class Booking {
public enum Status { NEW, PROGRESS, SUCCESS, FAILED }
private Status status;
public Status getStatus() {
return status;
}
}
Then you could test the Status.FAILED condition as follows:
<c:if test="${booking.status == 'FAILED'}">
Booking status is FAILED.
</c:if>
See also:
How to reference constants in EL?
As BalusC indicated, you cannot access enums using EL, however, you can do this:
<c:set var="enumFailed" value="<%=BookingStatus.FAILED%>"/>
<c:if test="${enumFailed.code == bookingInformation.bookingStatus}">
...
</c:if>
It would be ideal if bookingInformation.bookingStatus was an enum and not an int, but if re-factoring your app is out of the question due to its legacy nature, then my above example should help. You'd need a <c:set/> for each value of the enum (appears to just be two in your example).
You have to import the enum class in your jsp page. As far as you import it then you can refer to it. I wrote an example below.
My enum is the WebSettingType.
public enum WebSettingType {
SMTP_HOSTNAME("smtp_hostname"),
SMTP_PORT("smtp_port"),
SMTP_USERNAME("smtp_username");
private final String value;
private WebSettingType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
I have the websettings.jsp page that is uses a tag page etc.
<%#page import="my.package.WebSettingType"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:admin>
<jsp:attribute name="css">
</jsp:attribute>
<jsp:attribute name="content">
<input type="text" name="${WebSettingType.SMTP_HOSTNAME.getValue()}"/>
</jsp:attribute>
</t:admin>