Access Enum value using EL with JSTL

前端 未结 13 1967
迷失自我
迷失自我 2020-11-29 00:18

I have an Enum called Status defined as such:

public enum Status { 

    VALID(\"valid\"), OLD(\"old\");

    private final String val;

    Status(String va         


        
13条回答
  •  一生所求
    2020-11-29 00:30

    You have 3 choices here, none of which is perfect:

    1. You can use a scriptlet in the test attribute:

      This uses the enum, but it also uses a scriptlet, which is not the "right way" in JSP 2.0. But most importantly, this doesn't work when you want to add another condition to the same when using ${}. And this means all the variables you want to test have to be declared in a scriptlet, or kept in request, or session (pageContext variable is not available in .tag files).

    2. You can compare against string:

      This looks clean, but you're introducing a string that duplicates the enum value and cannot be validated by the compiler. So if you remove that value from the enum or rename it, you will not see that this part of code is not accessible anymore. You basically have to do a search/replace through the code each time.

    3. You can add each of the enum values you use into the page context:

      and then you can do this:

    I prefer the last option (3), even though it also uses a scriptlet. This is because it only uses it when you set the value. Later on you can use it in more complex EL expressions, together with other EL conditions. While in option (1) you cannot use a scriptlet and an EL expression in the test attribute of a single when tag.

提交回复
热议问题