views:

955

answers:

1

I'm trying to get an Action in Struts 2 to work with an Enum as an input parameter. What I've done so far looks like:

public TestAction {
  public enum Module {
    VALUE1;
  }

  private Module module;

  public void setModule(Module module) {
    this.module = module;
  }
  public Module getModule() {
    return module;
  }
}

But when trying to use this I get an xwork conversion error, and the action itself doesn't even execute. Can I make this work as is, or should I provide setModule(String) myself?

Edit: I'm using struts 2.1.6 The URL I'm trying: /test.action?module=value1

+2  A: 

It should bind a string to a enum straight away. I think the enum type converter has been in the default configuration since I think 2.1.x.

  • What version of struts 2 are you using?

if you are unsure the following is in my xwork-conversation.properties in a 2.0.14 app

java.lang.Enum = com.opensymphony.xwork2.util.EnumTypeConverter

EDIT: In response to the comment, if you need to ignore case for assigning an enum you have the following choices:

  • Change the value of enum to actaully be lower case - not great style and could make your code look a bit weird
  • Write a new case insensitive type converter for java.lang.Enum (just copy the xwork one and toUpper the input I guess)
  • add a new setModule(String) for this specific case
Gareth Davis
Sorry I forgot to mention I'm using struts 2.1.6. I read it was supposed to work out of the box while googling but it doesn't work for me the way I used it in the example above. An interceptor problem maybe?
wds
What does the query string look like.. /myAction.action?module=VALUE1 *should* just kinda work, binding stuff from the request to the action is the parameters interceptor, which if your getting a conversation error then it must already be configured
Gareth Davis
Okay it didn't occur to me somehow to test with VALUE1 instead of value1. It does indeed work that way. I guess the EnumTypeConverter uses Enum.valueOf, but I would really like to have it ignore case.
wds
just updated my answer with a couple of choices
Gareth Davis
Okay, thanks for your help.
wds
no worries, feel free to up vote my answer as well :)
Gareth Davis