Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC binding

I have the following command object:

public class User {
    private Department department;
    private String firstName;
    private String lastName;
    private String login;
    private String password;
...
}

which should be rendered at jsp page:

<form:input path="lastName" />
<form:input path="department.name"/>
<form:input path="department.description"/>

So when I submit with empty department.name and department.description the Spring auto-instantiate object Department with empty properties. (See https://jira.springframework.org/browse/SPR-6032 I would keep autoGrowNestedPaths=true)

What is need to do for getting back User object where Department object=null?

like image 611
eugenn Avatar asked Dec 16 '10 12:12

eugenn


1 Answers

What is need to do for getting back User object where Department object=null?

If you are looking for controller specific solution, then find all the empty nested params and set these params as disallowed fields.

@InitBinder(value="user")
    public void bind(WebDataBinder dataBinder, WebRequest webRequest) {
        List<String> emptyParams = new ArrayList<String>();
        Iterator<String> itr = webRequest.getParameterNames();
        while(itr.hasNext()) {
            String name = itr.next();
            if(name.startsWith("department.")) {
                Object value = webRequest.getParameter(name);
                if("".equals(value)) {
                    emptyParams.add(name);
                }
            }
        }
        if(!emptyParams.isEmpty()) {
            dataBinder.setDisallowedFields(emptyParams.toArray(new String[emptyParams.size()]));
        }
    }

If you are looking for a generic solution create a custom data binder and remove all nested params that are empty.

public class CustomDataBinder extends ServletRequestDataBinder {

    @Override
    protected void doBind(MutablePropertyValues mpvs) {
        PropertyValue[] pvArray = mpvs.getPropertyValues();
        for (PropertyValue pv : pvArray) {
            boolean nestedProperty = PropertyAccessorUtils.isNestedOrIndexedProperty(pv.getName());
            if(nestedProperty && "".equals(pv.getValue())) {
                mpvs.removePropertyValue(pv);
            }
        }
        super.doBind(mpvs);
    }

}

And to use CustomDataBinder you must have custom HandlerAdapter.

public class StandardAnnotationMethodHandlerAdapter extends AnnotationMethodHandlerAdapter    {
    @Override
    protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object target, String objectName) throws Exception {
    CustomDataBinder dataBinder = new CustomDataBinder (target, objectName);
    return dataBinder;
   }
}
like image 180
dira Avatar answered Oct 12 '22 21:10

dira