Struts 2迭代枚举

Pau*_*ich 10 java enums jsp struts2

在Struts 2中是否可以使用标记迭代枚举<s:iterator>?现在我正在使用String列表,但是可以直接使用枚举吗?

提前致谢.

Qua*_*ion 11

是.它有点难看,答案是启用静态方法访问,使用OGNL表达式的内部类语法(使用'$'),两者结合使用,然后让你获得Steven已经提到的values方法.这是一个例子:

示例操作:

package com.action.test;
import com.opensymphony.xwork2.ActionSupport;

public class EnumTest extends ActionSupport{
    enum Numbers{ONE, TWO, THREE};
}
Run Code Online (Sandbox Code Playgroud)

示例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>
Run Code Online (Sandbox Code Playgroud)

输出:


枚举测试

长度:3

ONE

TWO

THREE


注意:确保已启用静态方法访问.执行此操作的简单方法是<struts>在struts.xml中的标记之后添加以下内容.

<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
Run Code Online (Sandbox Code Playgroud)


Ste*_*tez 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

示例JSP

<s:iterator value="@example.SomeEnum@values()">
  <s:property value="name"/>
</s:iterator>
Run Code Online (Sandbox Code Playgroud)