Reputation: 14253
I have this hibernate model:
@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;
}
and this form:
<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>
and this controller method:
@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:/");
}
I set my creationDate
in the controller and other fields done by Spring form.
I suspect not setting creationDate
in the form caused getting bad request error on form submit.
What should I do to avoid this error?
Upvotes: 0
Views: 109
Reputation: 5115
Looks like same issue as Spring MVC Error: Failed to convert property value of type java.lang.String to required type.
That is, <form:select>
only submits a single string value, which you're telling Spring to put into a PostCategory
object.
Try telling it to put the value into the category
sub-object's id
field:
<form:select path="category.id">
Upvotes: 1