spring mvc验证和eleaf-validating integer字段

cu6pst1q  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(328)

我正在将.net项目移到SpringBoot。所以问题是如何在spring中正确验证整数字段。我有一个带有整数字段的实体:

  1. @Entity
  2. @Table(name = "tb_employee")
  3. public class EmployeeDev {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. @Column(name = "empl_id")
  7. private int emplId;
  8. @Range(min = 10, max = 50, message="Numbers only between 10 and 50")
  9. @Column(name = "default_vacation_days", nullable = true)
  10. private Integer defaultVacationDays;

... 以及捕捉错误的控制器:

  1. // update employee
  2. @PostMapping("/edit")
  3. public String showFormForUpdate(@Valid @ModelAttribute("employee") EmployeeDev employee, Errors errors,
  4. RedirectAttributes redirectAttributes,
  5. Model theModel) {
  6. if (null != errors && errors.getErrorCount() > 0) {
  7. List<ObjectError> errs = errors.getAllErrors();
  8. String errMsg = "";
  9. for (ObjectError e :errs)
  10. errMsg += e.getDefaultMessage();
  11. theModel.addAttribute("message", "Employee Edit failed. " + errMsg );
  12. theModel.addAttribute("alertClass", "alert-danger");
  13. return "employeesdev/employee-form-edit";
  14. }

现在的问题是,当我在default vacation days字段中键入超出范围的任何数字时,它将显示正确的验证消息:数字仅在10到50之间。
但是,如果我尝试插入类似1a(可能是用户输入错误)的内容,我会收到以下消息:无法将java.lang.string类型的属性值转换为属性defaultvacationdays所需的java.lang.integer类型;嵌套异常为java.lang.numberformatexception:对于输入字符串:“1a”
我知道这是正确的消息,但我讨厌向用户显示这样的消息。我更希望只显示“10到50之间的数字”,而不是数据类型转换问题。为什么要用java数据类型来烦扰用户呢?
如有任何建议,我将不胜感激。

uqxowvwt

uqxowvwt1#

如果您想从注解中获得自定义行为,则需要为该注解定义自己的constriant注解和验证器。
以下是自定义约束注解的基本示例:

  1. @Target({TYPE, ANNOTATION_TYPE})
  2. @Retention(RUNTIME)
  3. @Constraint(validatedBy = CheckCalculationTypeValidator.class)
  4. @Documented
  5. public @interface CheckCalculationType {
  6. String message() default "calculation_type shall be not NULL if status = active";
  7. Class<?>[] groups() default {};
  8. Class<? extends Payload>[] payload() default {};
  9. }

和验证程序:

  1. public class CheckCalculationTypeValidator implements ConstraintValidator<CheckCalculationType, RequestDto> {
  2. @Override
  3. public boolean isValid(RequestDto dto, ConstraintValidatorContext constraintValidatorContext) {
  4. if (dto == null) {
  5. return true;
  6. }
  7. return !(Status.ACTIVE.equals(dto.getStatus()) && dto.getCalculationType() == null);
  8. }
  9. @Override
  10. public void initialize(CheckCalculationType constraintAnnotation) {
  11. // NOP
  12. }
  13. }

hibernate验证程序所需的依赖关系:

  1. <dependency>
  2. <groupId>org.hibernate.validator</groupId>
  3. <artifactId>hibernate-validator</artifactId>
  4. <version>6.0.2.Final</version>
  5. </dependency>
展开查看全部

相关问题