我有这个hibernate模型:
@Entity
@Table(name="BlogPost")
public class BlogPost implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String title;
@Column
private String text;
@Column(name="creation_date")
private Date creationDate;
@ManyToOne
@JoinColumn(name = "cat_id")
private PostCategory category;
}
以及此表格:
<form:form action="saveBlogPost" method="post" modelAttribute="blogPost">
<table>
<form:hidden path="id"/>
<tr>
<td>Title:</td>
<td><form:input path="title" /></td>
</tr>
<tr>
<td>Text:</td>
<td><form:input path="text" /></td>
</tr>
<tr>
<td>Category:</td>
<td>
<form:select path="category">
<c:forEach items="${allCats}" var="cat" >
<form:option value="${cat.id}">
${cat.title}
</form:option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
和这个控制器方法:
@RequestMapping(value = "/saveBlogPost", method = RequestMethod.POST)
public ModelAndView saveEmployee(@ModelAttribute BlogPost blogPost) {
if (blogPost.getId() == 0) {
blogPost.setCategory(postCategoryServiceImpl.getPostCategory(blogPost.getCategory().getId()));
blogPost.setCreationDate(new Date());
blogPostServiceImpl.addBlogPost(blogPost);
} else {
blogPostServiceImpl.updateBlogPost(blogPost);
}
return new ModelAndView("redirect:/");
}
我将creationDate
设置在控制器中,并将其他字段设置为Spring表单。
我怀疑没有在表单中设置creationDate
导致在表单提交时出现错误的请求错误。
我该怎么做才能避免此错误?
答案 0 :(得分:1)
与Spring MVC Error: Failed to convert property value of type java.lang.String to required type看起来相同。
也就是说,<form:select>
只提交一个字符串值,您可以告诉Spring将其放入PostCategory
对象。
尝试告诉它将值放入category
子对象的id
字段:
<form:select path="category.id">