Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Jsr 303

900 Aufrufe

Veröffentlicht am

  • Als Erste(r) kommentieren

  • Gehören Sie zu den Ersten, denen das gefällt!

Jsr 303

  1. 1. JSR-303Bean Validation
  2. 2. Spring MVC Validatorpublic interface Validator { boolean supports(Class<?> clazz); void validate(Object target, Errors errors);}
  3. 3. Spring MVC Validator● Spring MVC specific● Can not be used on client side● All validation goes to single method● Hard to make unit tests
  4. 4. Description"This JSR will define a meta-data model and APIfor JavaBeanTM validation based on annotations,with overrides and extended meta-data throughthe use of XML validation descriptors."
  5. 5. Key points● Configured with annotations● Not tied to a specific application tier● Suits both server and client side
  6. 6. Implementations● Hibernate Validator (reference implementation)● Apache Bean Validation (incubation)● GWT Validation
  7. 7. Annotation samples @Min @Future @Null @Past @NotNull @Digits@MyCustomMegaConstraint @Max @Size @Pattern
  8. 8. Custom constraint sample@Target(TYPE)@Retention(RUNTIME)@Constraint(validatedBy = UniqueProductInOrderValidator.class)public @interface UniqueProductInOrder { String message() default "Only unique items"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};}
  9. 9. Bean sample@UniqueProductInOrderpublic class Item { private String product; @Valid private Order order; @NotBlank @Length(min = 5, max = 30) public String getProduct() { return product; }}
  10. 10. Validator samplepublic class UniqueProductInOrderValidator implements ConstraintValidator<UniqueProductInOrder, Item> { @Override public boolean isValid(Item v, ConstraintValidatorContext c) { Collection<Item> items = value.getOrder().getItems(); Set<Item> set = new HashSet<Item>(items); return set.size() == items.size(); }}
  11. 11. Invoke validation sample@RequestMapping(method = POST)public String create(@Valid Item item) { orderRepository.update(item.getOrder()); return "redirect:/orders/" + item.getOrder().getId();}@ExceptionHandler(BindException.class)public ModelAndView itemHasErrors(BindException e) { return new ModelAndView("addItem", e.getModel());}
  12. 12. Another sample@RequestMapping(value = "/orders", method = POST)public String create(@Valid Order order, BindingResult errors) { if (errors.hasErrors()) { return null; } orderRepository.save(order); return "redirect:/orders";}
  13. 13. Groups sample@GroupSequence({ Item.class, ComplexValidation.class })@UniqueProductInOrder(groups = ComplexValidation.class)public class Item { @NotBlank private String product;}interface ComplexValidation {}
  14. 14. Service layer validationpublic class SomeService { @Inject private Validator validator; public void doSomething(Item item) { Set<ConstraintViolation<Order>> violations = validator.validate(item); }}
  15. 15. Unit test sample@Testpublic void noValidationErrorsWhenItemIsValid() { Item item = new Item(order, "x", 0); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<Item>> violations = validator.validate(item); assertTrue(violations.isEmpty());}
  16. 16. Single property unit test sample@Testpublic void nullProductIsNotAllowed() { Item item = new Item(order, null, 0); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<Item>> violations = validator.validateProperty(item, "product"); assertFalse(violations.isEmpty());}
  17. 17. Hibernate Validator Annotation Processor Annotation processor based on JSR-269 which plugsinto the build process and raises compilation errorswhenever constraint annotations are incorrectly used.
  18. 18. https://github.com/aleksz/spring- reference

×