简体   繁体   中英

Spring MVC and form binding : how to tell Spring not to instantiate child objects if all their fields are empty?

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}"/>
...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM