Is it possible in Struts 2 to iterate an enum using the tag <s:iterator>
?
Right now I'm doing it using a list of String, but is it possible to use an enum directly?
Thanks in advance.
Yes. It is a bit ugly, the answer is enable static method access, use inner class syntax for the OGNL expression (uses the '$'), both in conjunction will let you then get at the values method as already mentioned by Steven. Here is an example:
Example Action:
package com.action.test;
import com.opensymphony.xwork2.ActionSupport;
public class EnumTest extends ActionSupport{
enum Numbers{ONE, TWO, THREE};
}
Example 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>
Output:
length: 3
ONE
TWO
THREE
<struts>
tag in struts.xml.
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
Sort of. You can't iterate an enum directly because its not a collection of values (an enum reference just represents one of the enum constants). However, you can iterate the values()
method of the enum, which is an array, or you can create an EnumSet
in your action and iterate that.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With