Passing a enum value as a tag attribute in JSP

jakubiszon picture jakubiszon · Nov 22, 2011 · Viewed 6.9k times · Source

I have a custom JSP tag which is using a parameter which is an enum. This approach is a consequence of using other classes which need this enumeration. The point is I have no clue how to assign an enum value in the EL:

<mytaglib:mytag enumParam="${now what do I type here?}" />

The only workaround which I found so far was to make the enumParam an Integer and convert it to desired values:

<mytaglib:mytag enumParam="3" />

I believe there must be a better way to do it. Please help.

Answer

devpg picture devpg · Nov 22, 2011

EL allows the use of Enums!

There are three ways to set a tag attribute value using either an rvalue or lvalue expression:
[..]

With text only:

<some:tag value="sometext"/>

This expression is called a literal expression. In this case, the attribute’s String value is coerced to the attribute’s expected type. Literal value expressions have special syntax rules. See Literal Expressions for more information. When a tag attribute has an enum type, the expression that the attribute uses must be a literal expression. For example, the tag attribute can use the expression "hearts" to mean Suit.hearts. The literal is coerced to Suit and the attribute gets the value Suit.hearts.

http://download.oracle.com/javaee/5/tutorial/doc/bnahq.html

Enum:

public Enum Color{ 
   RED, BLUE, GREEN 
}

JSP/ Tag file

<mytaglib:mytag enumParam="${'RED'}" />

Tested with Tomcat 7.0.22 as well as Jetty 6.1.26.