开发者

Struts 2 iterate enum

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:


Enum Test

length: 3

ONE

TWO

THREE


Note: Ensure that static method access is enabled. Simple way to do this is to add the following after the <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.

Example Enum

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();
  }
}

Example JSP

<s:iterator value="@example.SomeEnum@values()">
  <s:property value="name"/>
</s:iterator>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜