I have a spring form. The form contains a selection list associated with an enumeration type. I also added the "select" option to the selection list, which is not presented in the listing.
I saw some streams on the Internet where people suggest using a PropertyEditor to avoid having to change the enumeration and to avoid spring from converting error metadata between the "select" option and the enumeration (the user can leave this option as a choice - in some cases this is optional)
I created a PropertyEditor and tried it in two scenarios. If I try to use it with the selected list (as indicated below), the form will not load, and spring will cause errors: no const class com.mytest.domain.Box.Choose enumeration. If I don't turn on my custom editor, the form loads fine, and the only problem is when the form is submitted, the error object will contain errors complaining of a failed conversion from Java.lang.String to BoxType. If I switch the form to the form: input instead of the form: select, then the form will load and will only throw errors if I submit after entering a value that is not one of the Enum values. If I set a valid value, I see that my BoxEditor.setAsText() not being called. BoxEditor.getAsText() is called when the form is loaded (the monkey’s brain is the value in the input field). I wonder why the get method is called, but not the set. Any help would be greatly appreciated.
I defined Enum:
public enum BoxType { SMALL,MEDIUM,LARGE }
And the domain object:
public class BoxRequest { private BoxType box; public BoxType getBox() { return box; } public void setBox(BoxType b) { this.box = b; } }
I created jsp using jstl and spring form tagilb
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="s" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <html> <head> <title>Box Form</title> </head> <body> <form:form id="boxrequest" method="post" modelAttribute="boxrequest"> <form:label path="box">Choose a box size*</form:label> <form:input path="box"/> </form:form> </body> </html>
My PropertyEditor
public class BoxTypeEditor extends PropertyEditorSupport { @Override public void setAsText(String s) { System.out.println("This output is never printed :( "); if(StringUtils.hasText(s)) setValue(Enum.valueOf(BoxType.class, s)); else setValue(null); } @Override public String getAsText() { System.out.println("this output shows when the form loads"); if(getValue() == null) { return "monkeybrains"; } BoxType b = (BoxType) getValue(); return b.toString(); } }
source share