我正在尝试使用spring和Thymeleaf执行表单验证,但是当导航到表单URL时,我收到以下错误:
出现意外错误(type = Internal Server Error, 状态= 500)。执行处理器时出错 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (模板:“create-store-form” - 第18行,第28栏)
控制器
@RequestMapping(value="/createStoreForm.html")
public ModelAndView getCreateStoreForm() {
ModelAndView modelAndView = new ModelAndView("create-store-form");
return modelAndView;
}
@RequestMapping(value="/submitNewStoreForm" , method = RequestMethod.POST)
public ModelAndView submitNewStoreForm(@Valid @ModelAttribute("newStore") Store store, BindingResult bindingResult, HttpSession httpSession, Principal principal) {
String loggedInUsername = principal.getName();
User loggedInUser = userService.findUser(loggedInUsername);
ModelAndView modelAndView;
if(bindingResult.hasErrors()) {
modelAndView = new ModelAndView("create-store-form");
return modelAndView;
}
try {
store.setSellerName(loggedInUser.getUsername());
storeService.saveStore(store);
}catch (Exception e) {
modelAndView = new ModelAndView("create-store-form");
System.out.println("User '"+store.getName()+"' already exist on db.");
bindingResult.addError(new ObjectError("dup", "* Store '"+store.getName()+"' already exist!"));
return modelAndView;
}
modelAndView = new ModelAndView("store-page");
modelAndView.addObject("storeName", store.getName());
return modelAndView;
}
HTML
<div class="row">
<form action="#" th:action="@{/submitNewStoreForm}" th:object="${newStore}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Title error message</td>
</tr>
<tr>
<td>Image Link:</td>
<td><input type="text" th:field="*{imageLink}" /></td>
<td th:if="${#fields.hasErrors('imageLink')}" th:errors="*{imageLink}">Content error message</td>
</tr>
<tr>
<td><button type="submit">Submit post</button></td>
</tr>
</table>
</form>
</div>
我做错了什么?我跟着this guide。
答案 0 :(得分:0)
可能会出现此错误的原因有多种。
首先尝试以下操作:在getCreateStoreForm()
中,替换
... = new ModelAndView("create-store-form”);
... with:
... = new ModelAndView("create-store-form”, “newStore”, new Store());
"create-store-form”
= html表单视图名称“newStore”
=对象名称(th:thymeleaf中的对象)new Store()
=对模型对象的引用如果有效,请告诉我。如果没有,请发布完整的堆栈跟踪和Store
的类。