Java 使用 EL 和 JSTL 访问枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/123598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access Enum value using EL with JSTL
提问by IaCoder
I have an Enum called Status defined as such:
我有一个名为 Status 的 Enum 定义如下:
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
I would like to access the value of VALID
from a JSTL tag. Specifically the test
attribute of the <c:when>
tag. E.g.
我想VALID
从 JSTL 标记访问 的值。特别test
是<c:when>
标签的属性。例如
<c:when test="${dp.status eq Status.VALID">
I'm not sure if this is possible.
我不确定这是否可能。
采纳答案by Alexander Vasiljev
A simple comparison against string works:
与字符串的简单比较有效:
<c:when test="${someModel.status == 'OLD'}">
回答by IaCoder
So to get my problem fully resolved I needed to do the following:
因此,要完全解决我的问题,我需要执行以下操作:
<% pageContext.setAttribute("old", Status.OLD); %>
Then I was able to do:
然后我能够做到:
<c:when test="${someModel.status == old}"/>...</c:when>
which worked as expected.
这按预期工作。
回答by Alexander Vasiljev
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!
它看起来很丑,但有效!
回答by Eclatante
I generally consider it bad practice to mix java code into jsps/tag files. Using 'eq' should do the trick :
我通常认为将 java 代码混合到 jsps/tag 文件中是不好的做法。使用 'eq' 应该可以解决问题:
<c:if test="${dp.Status eq 'OLD'}">
...
</c:if>
回答by Dean
Add a method to the enum like:
向枚举添加一个方法,如:
public String getString() {
return this.name();
}
For example
例如
public enum MyEnum {
VALUE_1,
VALUE_2;
public String getString() {
return this.name();
}
}
Then you can use:
然后你可以使用:
<c:if test="${myObject.myEnumProperty.string eq 'VALUE_2'}">...</c:if>
回答by eremmel
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.:
我对 Kornel 的问题没有答案,但我对其他脚本示例有意见。大多数表达式都隐式地信任toString()
,但Enum.valueOf()
期望来自/匹配Enum.name()
属性的值。所以应该使用例如:
<% pageContext.setAttribute("Status_OLD", Status.OLD.name()); %>
...
<c:when test="${someModel.status == Status_OLD}"/>...</c:when>
回答by James
If using Spring MVC, the Spring Expression Language (SpEL) can be helpful:
如果使用 Spring MVC,Spring 表达式语言 (SpEL) 会有所帮助:
<spring:eval expression="dp.status == T(com.example.Status).VALID" var="isValid" />
<c:if test="${isValid}">
isValid
</c:if>
回答by Matt
You have 3 choices here, none of which is perfect:
您在这里有 3 个选择,没有一个是完美的:
You can use a scriptlet in the
test
attribute:<c:when test="<%= dp.getStatus() == Status.VALID %>">
This uses the enum, but it also uses a scriptlet, which is not the "right way" in JSP 2.0. But most importantly, this doesn't work when you want to add another condition to the same
when
using${}
. And this means all the variables you want to test have to be declared in a scriptlet, or kept in request, or session (pageContext
variable is not available in.tag
files).You can compare against string:
<c:when test="${dp.status == 'VALID'}">
This looks clean, but you're introducing a string that duplicates the enum value and cannot be validated by the compiler. So if you remove that value from the enum or rename it, you will not see that this part of code is not accessible anymore. You basically have to do a search/replace through the code each time.
You can add each of the enum values you use into the page context:
<c:set var="VALID" value="<%=Status.VALID%>"/>
and then you can do this:
<c:when test="${dp.status == VALID}">
您可以在
test
属性中使用 scriptlet :<c:when test="<%= dp.getStatus() == Status.VALID %>">
这使用了枚举,但也使用了 scriptlet,这在 JSP 2.0 中不是“正确的方式”。但最重要的是,当您想
when
使用${}
. 这意味着您要测试的所有变量都必须在 scriptlet 中声明,或者保存在请求或会话中(pageContext
变量在.tag
文件中不可用)。您可以与字符串进行比较:
<c:when test="${dp.status == 'VALID'}">
这看起来很干净,但是您引入了一个与枚举值重复且无法由编译器验证的字符串。因此,如果您从枚举中删除该值或重命名它,您将看不到这部分代码不再可访问。您基本上每次都必须通过代码进行搜索/替换。
您可以将您使用的每个枚举值添加到页面上下文中:
<c:set var="VALID" value="<%=Status.VALID%>"/>
然后你可以这样做:
<c:when test="${dp.status == VALID}">
I prefer the last option (3), even though it also uses a scriptlet. This is because it only uses it when you set the value. Later on you can use it in more complex EL expressions, together with other EL conditions. While in option (1) you cannot use a scriptlet and an EL expression in the test
attribute of a single when
tag.
我更喜欢最后一个选项 (3),尽管它也使用了 scriptlet。这是因为它仅在您设置值时使用它。稍后您可以在更复杂的 EL 表达式中使用它,以及其他 EL 条件。在选项 (1) 中,您不能在test
单个when
标记的属性中使用 scriptlet 和 EL 表达式。
回答by Pavan
In Java Class:
在 Java 类中:
public class EnumTest{
//Other property link
private String name;
....
public enum Status {
ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;
}
private Status statusobj ;
//Getter and Setters
}
So now POJO and enum obj is created. Now EnumTestyou will set in session object using in the servlet or controller class session.setAttribute("enumTest", EnumTest );
所以现在创建了 POJO 和 enum obj。现在EnumTest您将在 servlet 或控制器类 session.setAttribute("enumTest", EnumTest ); 中使用会话对象进行设置。
In JSP Page
在 JSP 页面中
<c:if test="${enumTest.statusobj == 'ACTIVE'}">
//TRUE??? THEN PROCESS SOME LOGIC
回答by Rupert Madden-Abbott
Here are two more possibilities:
这里还有两种可能:
JSP EL 3.0 Constants
JSP EL 3.0 常量
As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:
只要您使用的是至少 3.0 版的 EL,那么您就可以将常量导入您的页面,如下所示:
<%@ 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.
但是,一些 IDE 尚不理解这一点(例如IntelliJ),因此如果您输入错误,您将不会收到任何警告,直到运行时。
This would be my preferred method once it gets proper IDE support.
一旦获得适当的 IDE 支持,这将是我的首选方法。
Helper Methods
辅助方法
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:
然后在你的 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.
这在所有 IDE 中都受支持,如果您还不能使用 EL 3.0,也可以使用。这就是我目前所做的,因为它将所有逻辑都包含在我的枚举中。
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.
我认为这种方法优于在 JSP 中设置中间值的方法,因为您必须在需要使用枚举的每个页面上都这样做。但是,使用此解决方案,您只需声明一次 getter。