Spring MVC コントローラーを使用していて、値を に設定してフォームを送信すると、フォームにmodelAttribute
マップされていないモデルのフィールドの一部が失われます。この例では、年齢と住所をマップしていないため、これらのユーザーのフィールドは失われ、null
価値があります。ユーザーに年齢と住所を変更させたくないので、これらのフィールドはフォームにありません。
ユーザー編集フォームを投稿するメソッド コントローラー:
@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...
}
ユーザー編集ページを取得するためのメソッド コントローラー:
@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>
これらのフィールドの値を失わないための最善の解決策は何ですか? (年齢と住所)
各フィールドにフォームの隠しパスを使用する ?? 編集ページにリダイレクトする前にユーザーをセッションに保存し、ポストメソッドコントローラーでユーザーセッションを取得して、変更されたフィールドのみを変更しますか? 一般的な方法はありますか?