Passing a enum value as a tag attribute in JSP

99封情书 提交于 2019-12-12 09:34:58

问题


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");


来源:https://stackoverflow.com/questions/8223643/passing-a-enum-value-as-a-tag-attribute-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!