Spring MVC: Binding complex Objects to UI

后端 未结 1 1037
清歌不尽
清歌不尽 2021-02-06 02:17

I have my User Object which I am trying to bind to UI with spring MVC. User Object has another object Address in it.

public class User {
    String firstName;
          


        
相关标签:
1条回答
  • 2021-02-06 02:34

    To get your Address object back, you will need to list out each of the individual properties: for ex:

    <form:hidden path="user.address.street" />
    <form:hidden path="user.address.country" />
    

    and so on.

    Now, the object that you bind to the UI is the object that you passed from your controller. I am assuming that When the form gets submitted you want to get the User object back as a @ModelAttribute. In that case, you have two options: the first is that you will need to list out all the properties of your User object on the client-side (either as hidden objects or as visible form-elements).

    The second options is: you only display the required properties on the client-side, and rather than listing all the other propeties as hidden fields, you only keep the id of your User instance as a hidden field. Now, when you receive this @ModelAttribute upon form-submission, you can load the whole object from the database using the id and set the updated properties on it before calling update.

    for ex:

    @RequestMapping("updateUser.do")
    public String updateUser(@ModelAttribute User user, ... /* rest of the args */) {
        // ... some other code
        User existingUser = userService.findById(user.getId());
        existingUser.setFirstName(user.getFirstName());
        existingUser.setLasstName(user.getLastName());
    
        userService.update(existingUser);
        // ... rest of the code
    }
    

    There is no way that you can work only on the required-properties on the client-side, and merge it with that same existing object.

    0 讨论(0)
提交回复
热议问题