javaspringdata-bindingspring-mvcproperty-editor

Apply property editor to object in the model


I have a form and I have registered the CustomNumberEditor for the float numbers of my objects.

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

I have an ajax controller method to update a section of the form (it just returns an updated html fragment) so in the controller I do something like this:

public String retrieveFormSection(@PathVariable("id") String id, Model model) {
    ... 
    model.addAttribute("myObject", myObject);
    return "myJSP";
}

In that JSP I just want to print some data using the editors:

<input type="text" value="${myObject.myNumber}"/>

As myObject is not placed as a @ModelAttribute object the editor is not used for it. Is there any way to register the editors to the fields in the objects that I add to the model? Maybe editors should not be used for this because in this way I'm only using the getAsText() method of the editor and not in the setAsText(). Should I use another Spring feature for this?

Thanks.


Solution

  • You can use <spring:bind> to display value processed by PropertyEditor:

    <spring:bind path = "myObject.myNumber">
        <input type="text" value="${status.displayValue}"/> 
    </spring:bind>
    

    However, if you need to render it in the input field, you can also use <form:input>, as with regular forms. If you don't want it to be in a <form>, you can use <spring:nestedPath> instead of <form:form>:

    <form:form modelAttribute = "myObject">
        <form:input path = "myNumber" />
    </form:form>
    
    <spring:nestedPath path = "myObject">
        <form:input path = "myNumber" />
    </spring:nestedPath>