Spring configure mapping for nested form-objects

419 views Asked by At

I have the following classes

public class RequestResponseWrapper {

    MyDto myDto;

}

public class MyDto {

    private String field1;
    private String field2;
    ....
}

and I have the following controller method:

@RequestMapping(...)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public RequestResponseWrapper putData(@ModelAttribute RequestResponseWrapper requestResponseWrapper) {
        ....
}

I wrote following binder:

@InitBinder("requestResponseWrapper")
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(MyDto.class, new PropertyEditorSupport() {

            public void setAsText(String name) {
                setValue(StringUtils.isNotBlank(name) ? name : null);
            }
        });
}

Now If I got empty object from client it converts to the following structure:

requestResponseWrapper--
                        myDto--
                               field1 = null
                               field2 = null
                               ....

Expected result:

requestResponseWrapper--
                        myDto = null

How to change my code ?

1

There are 1 answers

2
zpontikas On

You should not set the value to null if its null. Just set it to the value you want (name) when your value is not null. I hope this makes sense.

    @InitBinder("requestResponseWrapper")
    public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(MyDto.class, new PropertyEditorSupport() {

                    public void setAsText(String name) {
                            if (StringUtils.isNotBlank(name)) {
                                    setValue(name);
                            }

                    }
            });
    }