Struts 2中是否可以使用标记<s:iterator>
迭代枚举?
现在我正在使用String列表,但是可以直接使用枚举吗?
提前致谢。
答案 0 :(得分:11)
是。它有点难看,答案是启用静态方法访问,使用OGNL表达式的内部类语法(使用'$'),两者结合使用,然后让你获得Steven已经提到的values方法。这是一个例子:
示例操作:
package com.action.test;
import com.opensymphony.xwork2.ActionSupport;
public class EnumTest extends ActionSupport{
enum Numbers{ONE, TWO, THREE};
}
示例JSP :
<%@taglib prefix="s" uri="/struts-tags"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<h1>Enum Test</h1>
//NOTE THE USE OF THE $ character to access the inner class on the following two lines.
length: <s:property value="@com.action.test.EnumTest$Numbers@values().length"/><br/>
<s:iterator value="@com.action.test.EnumTest$Numbers@values()">
<s:property/><br/>
</s:iterator>
</body>
</html>
<强>输出强>:
长度:3
ONE
二
三个
<struts>
标记之后添加以下内容。
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
答案 1 :(得分:8)
排序。您不能直接迭代枚举,因为它不是值的集合(枚举引用只表示枚举常量之一)。但是,您可以迭代枚举的values()
方法,这是一个数组,或者您可以在操作中创建EnumSet
并迭代它。
package example;
public enum SomeEnum {
ONE, TWO, THREE;
/* I don't recall if/how you can refer to non-getters in OGNL. */
public String getName() {
return name();
}
}
<s:iterator value="@example.SomeEnum@values()">
<s:property value="name"/>
</s:iterator>