我需要将枚举的所有值显示为 <option>
元素。我使用 scriptlet 实现了这一点:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="errors" tagdir="/WEB-INF/tags/jostens/errors" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<%
Class<?> c = CarrierCode.class;
for (Object carrier : c.getEnumConstants()) {
CarrierCode cc = (CarrierCode) carrier;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
out.print(formatter.format("<option value='%s'>%s</option>\n", cc.getMfCode(), cc.name()));
}
%>
...
但是,我想改为使用 JSTL/EL 代码来实现它。我该怎么做?
更新:
Spring 现在有一种更简单的方法来做到这一点。首先添加 Spring 框架工作标签
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
那么如果你只是声明一个选择,其中路径中的变量是一个枚举,
spring 自动找到其他元素。
<form:select path="dataFormat.delimiter" class="dataFormatDelimiter">
<form:options items="${dataFormat.delimiter}"/>
</form:select>
最佳答案
创建一个 ServletContextListener
在 webapp 启动期间将枚举值放入应用程序范围内的实现,以便它在 EL 中可用 ${carrierCodes}
.此类可重复用于您希望在 webapp 启动期间执行一次的所有其他操作。
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("carrierCodes", CarrierCode.values());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP
}
}
请注意,我使用了 Enum#values()
而不是笨拙的Class#getEnumConstants()
方法。它返回所有枚举值的数组。
然后,在 JSP 中,只需使用 JSTL <c:forEach>
对其进行迭代。
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="carrierCode">
<c:forEach items="${carrierCodes}" var="carrierCode">
<option value="${carrierCode.mfCode}">${carrierCode}</option>
</c:forEach>
</select>
关于java - 如何将枚举的所有值显示为 <option> 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6822611/