I have an Enum called Status defined as such:
public enum Status {
VALID(\"valid\"), OLD(\"old\");
private final String val;
Status(String va
A simple comparison against string works:
<c:when test="${someModel.status == 'OLD'}">
I do not have an answer to the question of Kornel, but I've a remark about the other script examples. Most of the expression trust implicitly on the toString()
, but the Enum.valueOf()
expects a value that comes from/matches the Enum.name()
property. So one should use e.g.:
<% pageContext.setAttribute("Status_OLD", Status.OLD.name()); %>
...
<c:when test="${someModel.status == Status_OLD}"/>...</c:when>
Here are two more possibilities:
As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:
<%@ page import="org.example.Status" %>
<c:when test="${dp.status eq Status.VALID}">
However, some IDEs don't understand this yet (e.g. IntelliJ) so you won't get any warnings if you make a typo, until runtime.
This would be my preferred method once it gets proper IDE support.
You could just add getters to your enum.
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
public boolean isValid() {
return this == VALID;
}
public boolean isOld() {
return this == OLD;
}
}
Then in your JSP:
<c:when test="${dp.status.valid}">
This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.
Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:
<c:when test="${not empty db.status and dp.status.valid}">
I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.
<%@ page import="com.example.Status" %>
1. ${dp.status eq Title.VALID.getStatus()}
2. ${dp.status eq Title.VALID}
3. ${dp.status eq Title.VALID.toString()}
If using Spring MVC, the Spring Expression Language (SpEL) can be helpful:
<spring:eval expression="dp.status == T(com.example.Status).VALID" var="isValid" />
<c:if test="${isValid}">
isValid
</c:if>
For this purposes I do the following:
<c:set var="abc">
<%=Status.OLD.getStatus()%>
</c:set>
<c:if test="${someVariable == abc}">
....
</c:if>
It's looks ugly, but works!