Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
Paul Ulrich Avatar asked Jul 15 '11 14:07

Paul Ulrich


2 Answers

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"/>
like image 69
Quaternion Avatar answered Oct 05 '22 11:10

Quaternion


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>
like image 35
Steven Benitez Avatar answered Oct 05 '22 10:10

Steven Benitez