When I'm using a Spring MVC controller and I submit a form by setting value to the modelAttribute
I lose some of the model's fields which are not mapped in the form.
In this example, because I didn't map age and address, these user's fields are lost and so they have null
value. I don't want to let the user change their age and the address, that's why these fields are not in the form.
Method controller to post user edit form:
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String editionUser(Model model, @ModelAttribute("accountForm") User user,
BindingResult bresult,
RedirectAttributes redirectAttributes) {
//user.getAge() and user.getAddress are null
//Save the information...
}
Method controller to get edit user page:
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String initEdit(Model model) {
// the user fields are all filled
User user = userService.getUserById(...);
model.addAttribute("accountForm", user);
return "edition";
}
class User {
Long id;
String email;
String age;
String address;
String nickname;
// ...
}
edition.jsp
<form:form class="form" method="POST" action="edition" modelAttribute="accountForm">
<form:label path="email">email</form:label>
<form:input path="email" name='email'/>
<form:label path="nickname">nickname</form:label>
<form:input path="nickname" name='nickname'/>
<form:hidden path="id" />
<input name="submit" type="submit" value="valid" />
</form:form>
What are the best solution to not lose the value of these fields ? (age and address)
Use form hidden path for each field ?? Store the user in session before redirect to the edit page and set retreive the user session in post method controller to only change the modified fields ? Is there a generic method?