开发者

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 ob开发者_如何学Cject 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?


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;
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜