@Valid我做错了什么?

时间:2017-01-02 17:11:52

标签: spring-boot thymeleaf

我正在尝试使用@Valid表示法验证表单。基本上现在我只想让author字段不为空,如果我能让它工作,我会把它扩展到其他所有字段。

这是我的豆子:

@SuppressWarnings("serial")
@Entity
@Table(name = "Document")
public class Document implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @NotNull @NotEmpty
    private String author;
    @NotNull
    private String pubDate;
    @NotNull
    private String title;
    @NotNull
    private String editor;

    private String uploadDate;
    private String contentType;
    private long size;
    private Blob content;
    //setters & getters

这是我正在使用的表格:

<form th:action="@{/upload}" method="post"
    enctype="multipart/form-data">
    <p>
        Author: <input name="author" type="text" th:value="${doc.author}" />
    </p>
    <p th:if="${#fields.hasErrors('doc.author')}"
        th:errors="${doc.author}">Name error</p>
    <p>
        Publication date: <input name="pubDate" type="text"
            th:value="${doc.pubDate}" />
    </p>
    <p>
        Title: <input name="title" type="text" th:value="${doc.title}" />
    </p>
    <p>
        Editor: <input name="editor" type="text" th:value="${doc.editor}" />
    </p>
    <p>
        Content: <input name="formContent" type="file"
            th:value="${content.formContent}" />
    </p>
    <!--  <p>Content: <input name="contentFromForm" type="file" th:value="${doc.contentFromForm}"/></p>-->
    <p>
        <input type="submit" value="Upload" /> <input type="reset"
            value="Reset" />
    </p>
</form>

控制器在发送时管理表单:

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String uploadtoDB(@Valid @ModelAttribute(value = "doc") Document doc,
        @ModelAttribute(value = "content") Content content, Model model, BindingResult bindingResult)
        throws SerialException, SQLException, IOException {

    if (bindingResult.hasErrors())
        return "upload";

    doc.setContent(new javax.sql.rowset.serial.SerialBlob(content.getFormContent().getBytes()));
    doc.setContentType(content.getFormContent().getContentType());
    doc.setSize(content.getFormContent().getSize());
    doc.setUploadDate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()).toString());

    documentDAO.save(doc);
    return "uploadOk";
}

所以基本上我使用的是NotNull,应该通过@Valid @ModelAttribute(value = "doc") Document doc进行检查。并且错误应该显示为:

        <p th:if="${#fields.hasErrors('doc.author')}" th:errors="${doc.author}">Name error</p>

Cleary我做错了,因为当我将作者字段留空时,表单发送没有任何问题。但是我做错了什么?感谢。

0 个答案:

没有答案
相关问题