Spring MVC和表单绑定:如果子对象的所有字段为空,如何告诉Spring不要实例化子对象? [英] Spring MVC and form binding : how to tell Spring not to instantiate child objects if all their fields are empty?

查看:47
本文介绍了Spring MVC和表单绑定:如果子对象的所有字段为空,如何告诉Spring不要实例化子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果他的字段没有被相应的表单修改,那么我很难理解如何阻止Spring初始化表单bean的子成员对象.例如,我有一个具有地址"字段的用户对象",我将空的用户"实例传递给表单(地址"当时为null).在表单中,我具有所有用户以及地址字段的输入字段:

I have trouble to understand how to stop Spring from initializing the child member object of a form bean if none of his fields were modified by the corresponding form. For example I have an User Object that has a field Address, I pass the empty User instance to the form (the Address is null at the time). In the form I have input fields for all User as well as Address fields:

<form action="#" th:action="@{/user/add}" th:object="${user}" method="post">
...
<input type="text" th:field="*{address.street}"/>
<input type="text" th:field="*{firstName}"/>
...

当我在相应的控制器方法中设置断点时,Address对象存在于User对象中,并且其所有字段均为null,0,false(默认值).我知道初始化发生在WebDataBinder中.我如何指示它不这样做?对于动态列表,也会发生同样的情况,如果我有列表,则在表单提交后,列表将获得一个新条目.非常感谢您的帮助

when I set a breakpoint in the corresponding controller method, the Address object exist within the User object and all its fields are null,0,false(default values). I know the initialization occurs in the WebDataBinder. How can I instruct it not to do so? The same happens with the dynamic lists, if i had List then the List would get a new entry after form submit. Would really appreciate any help

推荐答案

您需要实例化该对象,否则您将无法将在表单中输入的值存储在任何地方.

You need that object instantiated or you could not store the values entered in the form anywhere.

如果您不想将空对象保存到数据库,则可能需要在修改之前检查它,然后再保存.

If you don't want to save the empty object to the DB then you probably need to check it on modification before saving.

这篇关于Spring MVC和表单绑定:如果子对象的所有字段为空,如何告诉Spring不要实例化子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆