java 我可以使用 EL 从 JSP 访问枚举类的值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2240722/
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
Can I access the values of an enum class from a JSP using EL?
提问by Eric Wilson
I have an enum class USState. I would like to iterate through the states in a JSP.
我有一个枚举类USState。我想遍历 JSP 中的状态。
Is it possible to access a list of USStates without first setting such a list as an attribute? It seems that something as static as an enum should always be available, but I can't figure out how to do it.
是否可以在USState不首先将此类列表设置为属性的情况下访问s 列表?似乎像枚举一样静态的东西应该总是可用的,但我不知道如何去做。
Here's what I'm looking for: (except working)
这就是我要找的:(工作除外)
<c:forEach var="state" items="${USState.values}" >
<option value="${state}">${state}</option>
</c:forEach>
回答by Bozho
You will have to create a list somewhere on your backing code and pass it as a model parameter. Preferably in an ServletContextListener(as advised by BalusC) and put it in the ServletContext(i.e. application scope):
您必须在支持代码的某处创建一个列表并将其作为模型参数传递。最好在ServletContextListener(如 BalusC 所建议的)中并将其放在ServletContext(即应用范围)中:
servletContext.setAttribute("statesList", YourEnum.values());
回答by BalusC
You can also consider to wrap it in a Javabean like follows:
您还可以考虑将其包装在 Javabean 中,如下所示:
package com.stackoverflow.q2240722;
public class StateBean {
public State[] getValues() {
return State.values();
}
}
This way it's accessible by <jsp:useBean>:
这样它就可以通过<jsp:useBean>以下方式访问:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:useBean id="stateBean" class="com.stackoverflow.q2240722.StateBean" />
<!doctype html>
<html lang="en">
<head>
<title>SO question 2240722</title>
</head>
<body>
<select>
<c:forEach items="${stateBean.values}" var="state">
<option value="${state}">${state}</option>
</c:forEach>
</select>
</body>
</html>
回答by axtavt
Note that you can also use a scriptlet (I don't think it's too harmful in such a simple case):
请注意,您也可以使用 scriptlet(我认为在这种简单的情况下它不会太有害):
<c:forEach var="state" items="<%= USState.values() %>" >
(USStateshould be either fully qualified or imported using <%@ page import = "..." %>
(USState应该是完全合格的或使用导入的<%@ page import = "..." %>

