未填写所有Spring表单字段并获取错误请求错误400

时间:2018-05-23 15:44:07

标签: java spring hibernate spring-mvc jstl

我有这个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导致在表单提交时出现错误的请求错误。

我该怎么做才能避免此错误?

1 个答案:

答案 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">