程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证?

开发过程中遇到Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证的问题如何解决?下面主要结合日常开发的经验,给出你关于Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证的解决方法建议,希望对你解决Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证有所启发或帮助;

JsR-303强制使用@ValID批注来递归地验证嵌套组件,如Hibernate Validator文档中所述。

因此,只需将@ValID嵌套的组件放在雇员类中的Department字段中:

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

解决方法

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

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

   @NotEmpty
   private String name;
}

还有另一个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;
}

上面的代码在员工表单中使用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';
}

这是员工表格

 <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字段)?

注意:我不使用drowpdownlist来显示部门信息,而是希望使用带有所选部门ID的自动完成字段和隐藏字段。

大佬总结

以上是大佬教程为你收集整理的Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证全部内容,希望文章能够帮你解决Spring注解:使用Thyme leaf对Bean内部对象属性的形式验证所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。