我在某处读到过,对于 spring mvc,如果表单不包含 @ModelAttribute 注释设置的模型对象的所有属性,则返回 NULL 是一种预期的行为。我如何使用没有模型对象的所有字段的表单,并且仍然将整个但更新的对象接收回控制器的 post 方法。
我的意图的简短示例代码:
控制器部分:
....
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String editPost(Model model, @PathVariable Integer id) {
model.addAttribute("editPost", bPostService.getPost(id));
return "editPost";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String editProcessPost(Model model, @PathVariable Integer id, @ModelAttribute BPost editPost) {
bPostService.updatePost(editPost);
model.addAttribute("posts", bPostService.getPosts());
return "redirect:/";
}
....
hibernate映射的实体:
@Entity
@Table(name = "sometable")
public class BPost {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "text")
private String text;
@Column(name = "anothertext")
private String anothertext;
// getters and setters
}
JSP 视图的一部分:
<form:form method="POST" modelAttribute="editPost" action="${pageContext.request.contextPath}/secure/post/edit/${editPost.id}">
<table>
<tbody>
<tr>
<td>title:</td>
<td><form:input path="title"></form:input></td>
</tr>
<tr>
<td>description:</td>
<td><form:input path="description"></form:input></td>
</tr>
<tr>
<td>text:</td>
<td><form:input path="text"></form:input></td>
</tr>
<tr>
<td><input value="Edit" type="submit"></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
如您所见,JSP 上没有使用“anothertext”属性,但我不希望它原封不动地返回到控制器的 POST 方法。那可能吗?
我知道有人可能已经问过这个问题,但我找不到答案。
感谢!