ELum line processing

I have a variable passed to my JSP view from a spring controller that maps to an enumeration. It is printed in "ENUM_VALUE", not very user friendly.

What is the best way to convert this to a more readable form like "Enum value".

I would prefer a pure EL solution to avoid writing more code in the controller to parse it, but all comments are appreciated.

+3
source share
4 answers

This value comes from the method Enum#name(). Just add a getter to your enum, which returns a friendly name. For instance.

public String getFriendlyName() {
    return name().toLowerCase().replace("_", " ");
}

EL ${bean.someEnum.friendlyName}.

+5

, . - .

public enum MyEnum {

    ENUM_VALUE("your friendly enum value");

    private String description;

    //constructor
    private MyEnum(String description) {
        this.description = description;
    }

    //add a getter for description
}

EL ${yourenum.description}

+1

Kacper86, 2.1 , Enum-to-String .name() toString(). BalusC .

EL getDescription . , toString(), . Java, toString(), EL. , EL , enum , -; EL .

EL-:

public final class JSTLUtilityFunctions 
{
    public static String enumToStr(Enum<?> enumInst) {
        return enumInst.toString();
    }
}

TLD:

<taglib>
    <!-- Other stuff... -->
    <function>
        <name>enumToStr</name>
        <function-class>yourpackage.JSTLUtilityFunctions</function-class>
        <function-signature>java.lang.String enumToStr(java.lang.Enum)</function-signature>
    </function>
</taglib>

:

<%@taglib prefix="util" uri="your-TLD-uri.tld" %>
<span>${ util:enumToStr(myEnumInstance) }</span>

, , Object, .

0
source

You can just do something like this in jsp:

<span>${myenum.toString()}</span>
-1
source

Source: https://habr.com/ru/post/1771746/


All Articles