Passing a enum value as a tag attribute in JSP

2020-08-15 10:38发布

问题:

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.

回答1:

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.



回答2:

EL does not support accessing Enums. You should consider using strings .

Example:

public Enum Color{ 
   READ, BLUE, GREEN 
}

You can pass string to your custom tag like below:

<mytaglib:mytag enumParam="RED" />
OR
<mytaglib:mytag enumParam="${obj.color}" />

In your custom tag you get the enum value like this:

Color.valueOf("RED");


标签: jsp enums taglib