我有一个枚举类 USState
。我想遍历 JSP 中的状态。
是否可以在不首先将这样的列表设置为属性的情况下访问 USState
的列表?似乎像枚举这样静态的东西应该始终可用,但我不知道该怎么做。
这是我要找的:(工作除外)
<c:forEach var="state" items="${USState.values}" >
<option value="${state}">${state}</option>
</c:forEach>
最佳答案
您也可以考虑将其包装在一个 Javabean 中,如下所示:
package com.stackoverflow.q2240722;
public class StateBean {
public State[] getValues() {
return State.values();
}
}
这样可以通过<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>
关于java - 我可以使用 EL 从 JSP 访问枚举类的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240722/