简体   繁体   中英

How to validate two or more beans in a Spring Controller method with Hibernate Validator (JSR 303)

I have two classes (Beans)

public class BeanOne {
  @Min(1)
  private Integer idBeanOne;
  @NotBlank
  private String  nameBeanOne;
  @NotNull
  @Min(1)
  private Integer idOther;
  // ... Getters and Setters
}

public class BeanTwo {
  @Min(1)
  private Integer idBeanTwo;
  @NotBlank
  private String  nameBeanTwo;
  @NotNull
  @Min(1)
  private Integer idOtherTwo;
  // ... Getters and Setters
}

Controller of Spring

// Method in Controller
@RequestMapping(value = "/name.html", method = RequestMethod.POST)
public @ResponseBody
Map<String, Object> submitInsert(@Valid BeanOne one,
    @Valid BeanTwo two, BindingResult result) {

  if (result.hasErrors()) {
    // Errores
  } else {
    // :D
  }
}

Is there any way that I can validate two or more beans? I have successfully validated a single bean, but I have not been successful in validating two or more beans. How can I do this? thanks: D thanks: D

After many attempts to validate two or more beans with JSR303, come to this solution.

public class BeanOne {
  @Valid
  private BeanTwo beanTwo;
  // other beans to validate
  @Valid
  private BeanN beanN;

  @Min(1)
  private Integer idBeanOne;
  @NotBlank
  private String  nameBeanOne;
  @NotNull
  @Min(1)
  private Integer idOther;
  // ... Getters and Setters
}

public class BeanTwo {
  @Min(1)
  private Integer idBeanTwo;
  @NotBlank
  private String  nameBeanTwo;
  @NotNull
  @Min(1)
  private Integer idOtherTwo;
  // ... Getters and Setters
}

// Controller Spring

@Controller
public class XController {

  @Autowired
  private Validator validator;

  @RequestMapping(value = "/name.html", method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> 
     submitInsert(BeanOne beanOne, BeanTwo beanTwo, BindingResult  result) {

    beanOne.setBeanTwo(beanTwo);
    // beanOne.setBeabN(beanN);
    validator.validate(beanOne, result);

    if (result.hasErrors()) {
      // Errores
    } else {
      // :D
    }
  }
  // more code ...
}

But now I have another problem :(

I have this file Messages.properties

typeMismatch.java.lang.Integer = Must specify an integer value. 
typeMismatch.java.lang.Long = Must specify an integer value. 
typeMismatch.java.lang.Float = Must specify a decimal value. 
typeMismatch.java.lang.Double=Must specify a decimal value.

This file helps me to catch exceptions, when a field expects a number, and the user enters text

This works perfectly for the first bean (BeanOne) but not for nested beans (BeanTwo, BeanN)

I hope they can help me: D

thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM