我目前在一个项目中使用下面的代码,我遇到的问题是即使在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是一个非常常用的东西)。 –