我试图验证表单。 Spring正确验证,但是当应该返回错误时,它会收到异常:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'employee' available as request attribute
添加我不知道出了什么问题。你能帮帮我吗?
控制器:
@RequestMapping(value = "/employee/add",method = RequestMethod.POST)
public String addEmployee(@Valid DTOEmployee dtoEmployee, BindingResult result) {
if (result.hasErrors()) {
return "employee_add";
}
employeeService.save(dtoEmployee);
return "redirect:/employee?add";
}
DTOEmployee:
public class DTOEmployee{
@NotNull
private String name;
@NotNull
private String subname;
@NotNull
private String email;
}
employee_add的片段:
<form th:action="@{/employee/add}" th:object="${employee}" method="post" class="form-inline justify-content-center">
<div class="input-group my-1">
<input th:field="*{name}" type="text" id="name" class="form-control"
placeholder="Your name"/>
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name error</p>
<input th:field="*{subname}" type="text" id="name" class="form-control"
placeholder="Your subname"/>
<p th:if="${#fields.hasErrors('subname')}" th:errors="*{name}">Name error</p>
<input th:field="*{email}" type="email" id="email" class="form-control"
placeholder="Your mail"/>
<p th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name error</p>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
messages.properties:
NotNull.DTOEmployee.name = Name must be not null
NotNull.DTOEmployee.subname= Subname must be not null
NotNull.DTOEmployee.email= Email must be not null
答案 0 :(得分:0)
好像你正在将thymeleaf表单提交与请求混合。如spring.io https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweets-id
中的示例所述@ModelAttribute
好像你错过了port.readline()
答案 1 :(得分:0)
嗯...我添加了@ModelAttribute [public String addEmployee(@Valid @ModelAttribute DTOEmployee dtoEmployee,BindingResult result)],我得到以下异常:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "employee_add" - line 44, col 44)] with root cause
employee_add中的第44行是:
<input th:field="*{name}" type="text" id="name" class="form-control"
我忘了在引号中添加属性名称:
public String addEmployee(@Valid @ModelAttribute("employee") DTOEmployee dtoEmployee, BindingResult result)
它的工作:)