我目前在一個項目中使用下面的代碼,我遇到的問題是即使在bindingresult(bindingResult.hasErrors()爲true)中存在錯誤時,它也呈現爲false百里香的結果。這使我認爲bindingResult沒有被正確注入。我在下面的代碼中做了什麼錯誤?字段錯誤和globalerrors在Thymeleaf中保持空白
<form action="blog.html" th:action="@{/fileUpload}" method="post"
enctype="multipart/form-data" th:object="${form}">
<input type="text" name="title" th:field="*{title}" /> <input
type="text" name="content" th:field="*{content}" /> <input
type="file" name="myFile" th:field="*{myFile}" /> <input
type="submit" />
<div id="errors" class="alert alert-error">
<ul th:if="${#fields.hasErrors('*')}">
<li th:each="err : ${#fields.errors('*')}" th:text="${err}"></li>
</ul>
<div th:if="${#fields.hasGlobalErrors()}">
<p th:each="err : ${#fields.globalErrors()}" th:text="${err}">...</p>
</div>
</div>
</form>
控制器
@RequestMapping(value = "/blog", method = RequestMethod.GET)
public String getIndex(Model model) {
model.addAttribute("form", new AddBlogForm());
return "blog";
}
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public String importParse(Model model, @Valid AddBlogForm form, BindingResult bindingResult) {
model.addAttribute("form", form);
try {
if (!bindingResult.hasErrors()) {
model.addAttribute("successmessage", "Succesfully added");
blogSrv.addPost(form.getTitle(), form.getContent(), form.getMyFile());
model.addAttribute("form", new AddBlogForm());
}
return "blog";
} catch (IllegalStateException e) {
bindingResult.addError(new ObjectError("image", "IllegalStateException occured " + e.getMessage()));
return "blog";
} catch (IOException e) {
bindingResult.addError(new ObjectError("image", "IOException occured " + e.getMessage()));
return "blog";
}
}
刪除'Model'屬性,並添加'@ ModelAttribute'你'AddBlogForm'方法參數。成功保存重定向到你的'/ blog'網址。 (Post-redirect-get是一個非常常用的東西)。 –