Search This Blog

Wednesday, July 19, 2017

Spring JSP Enum in Select/Combo box

This post demonstrate that how to use Enum values in JSP page with Spring Framework


Java Class:

public class User{
    private String name;
    private UserType userType;

    setter and getter
}



Enum Class:

public enum UserType {
    ADMIN("Admin"), USER("User"), TEACHER("Teacher"), STUDENT("Student");

    private String code;

    UserType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }


    public static UserType fromCode(String userType) {
        for (UserType uType : UserType.values()) {
        if (uType.getCode().equals(userType)) {
            return uType;
        }
        }
        throw new UnsupportedOperationException("The code " + userType + " is not supported!");
    }
}






 In controller you need to set model as below:

ModelAndView model = new ModelAndView("/home/index");

model.addObject("user", new User());
model.addObject("types", UserType.values());



 In JSP you can get it as below:

<form:select path="userType">
        <form:option value="" label="Chose Type" />
        <form:options items="${types}" itemLabel="code"  />
</form:select>

No comments:

Post a Comment