春季注释:使用百里叶的bean内部对象属性形成验证



在胸腺中有没有办法在bean的对象属性中验证属性?认为我们确实有一个部门课程:

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

和另一个员工类如下

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;
}

使用上面的代码使用雇员表格中的百里叶"雇员",将通过春季验证,因为注释。让我们在这里看看在我的控制器

@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';
}

,这是员工表格

 <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>

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

nb:我不使用drowpdownlist来显示部门,而是喜欢自动完成字段和一个隐藏的字段,该字段将选中选择的部门ID。

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

因此,只要将@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;
}

最新更新