Spring 注释:使用 thymeleaf 对 bean 内部对象属性进行表单验证

Cfa*_*ing 2 java spring-mvc thymeleaf spring-boot jakarta-ee

Thymeleaf 中有没有办法验证 bean 的对象属性中的属性?考虑到我们确实有一个 Departement 类,如下所示:

public class Departement {
   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long idDept;

   @NotEmpty
   private String name;
}
Run Code Online (Sandbox Code Playgroud)

另一个 Employee 类如下

public class Employee{
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long idEmp;

  @NotEmpty
  @Size(min = 5, message="At least five characters needed")
  private String employeeName;

  @NotNull
  private Departement departement;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在员工表单中使用 thymeleaf 时,只有“employeeName”会因为注释而被 spring 验证。让我们看看这里在我的控制器中

@GetMapping( value = "/emp" )
public String save(Model model){
  Employee emp = new Employee();
  emp.setDepartement(new Departement());
  model.addAttribute('employee', emp);
  return 'view';
}
//------------- Form in PostMapping
@PostMapping( value = "/save", @Valid Emp emp, BindingResult bindingResult )
public String savePost(Model model){
if( ! bindingResult.hasErrors() )
    {
 /* Even if departement has not been choosen, my code always goes here 
and print "Form Ok. Departement : 0" instead of reaching the 'else' block, but if departement choosen, 
it prints the correct value of departemnt 
*/
      System.out.println( "Form Ok.\n Departement : " + emp.getDepartement().getIdDept() );
  }else{
           System.out.println( "Missing attributes." );
  }

  return 'view';
}
Run Code Online (Sandbox Code Playgroud)

这是员工表格

 <form th:action="@{save}" th:object="${emp}" th:method="POST" >
  <span th:if="${#fields.hasErrors('employeeName') }"th:errors="*{employeeName}"></span>
    <input th:field="*{employeeName}" th:value="${employeeName}" />
//--------
   <div th:object="${emp.departement}">
      <span th:if="${#fields.hasErrors('idDept') }"th:errors="*{idDept}"></span>
      <input th:field="*{idDept}" th:value="${idDept}" />
   </div>
</form>
Run Code Online (Sandbox Code Playgroud)

**这是我的问题:如何在不使用 emplpoyee 表单中的 javacript 的情况下验证员工部门标识符(idDept 字段)?**

注意:我不使用 drowpdownlist 来显示部门,但更喜欢自动完成字段和采用所选部门 ID 的隐藏字段。

Ste*_*erl 6

JSR-303 要求使用@Valid注解来递归验证嵌套组件,如Hibernate Validator 文档中所述

因此,只需放置@Valid您的嵌套组件,就您而言,放置在员工类中的部门字段上:

public class Employee {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long idEmp;

  @NotEmpty
  @Size(min = 5, message="At least five characters needed")
  private String employeeName;

  @NotNull
  @Valid 
  private Departement departement;
}
Run Code Online (Sandbox Code Playgroud)