【发布时间】:2016-06-04 18:38:25
【问题描述】:
我有实体:
@Entity
public class News
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String content;
private boolean isMain;
}
按下编辑按钮后,我可以按表单编辑标题和内容:
@RequestMapping(value = "/edit/{newsId}", method = GET)
public String edit(@PathVariable long newsId, Model model)
{
News news = newsService.getById(newsId); //hibernate
model.addAttribute("news", news);
return "admin";
}
表格:
<form method = "POST" th:object = "${news}" th:action="@{/news/editNews}" id = "add_news_form">
<input type = "text" th:field = "*{title}" th:value="*{title}" />
<input type = "submit" value = "Edit" /><br>
<textarea name = "news_content" rows = "20" cols = "80" th:field = "*{content}" th:text= "*{content}" form = "add_news_form" >Wpisz... </textarea>
</form>
和POST方法:
@RequestMapping(value = "/editNews", method = POST)
public String editNews( News news )
{
newsService.update(news); //hibernate
return "redirect:/";
}
它给出了 null 异常,因为 post 方法中的 news 对象只有 title 和 content 字段不为 null。我可以为设置 id 添加文本输入,但用户不能这样做。如果我有 100 个其他字段并且我想以表单形式保存在那里并且只更改它们的两个字段怎么办?
【问题讨论】:
-
尝试将参数映射到控制器中的表单:
public String editNews(@ModelAttribute("news" ) News news )