Вы находитесь на странице: 1из 14

JSR 303 Bean Validation Introduction

the sbva project

Quick Code Example


publicclassCar{ @NotNullprivateStringmanufacturer; @NotNull@Size(min=2,max=14)privateStringlicensePlate; @Min(2)privateintseatCount; publicCar(Stringmanufacturer,StringlicencePlate,intseatCount){ this.manufacturer=manufacturer; this.licensePlate=licencePlate; this.seatCount=seatCount; } //gettersandsetters... }

Specification Goals

Defines a metadata model and API for JavaBean validation using annotations which can be overridden by xml. Using metadata ensures that domain classes are not cluttered with validation code. This API is seen as a general extension to the JavaBeans object model, and as such is expected to be used as a core component in other specifications Ease of use and flexibility have influenced the design of this specification. JSF and JPA are targeted by this specification

Existing Validation Technology

Commons-validation

Pros : widely used and understood Cons : difficult to unit test, awkward syntax, hard to reuse

http://www.i-screen.org/docs/index.html http://oval.sourceforge.net/ Plus a million other validation frameworks searchable with Google Write your own from scratch

How To Implement Validators

Implementing a constraint requires


One constraint definition implementing @javax.validastion.Constraint per constraint A constraint validation implementation implementing @javax.validation.ConstraintValidator<Constr aint, Type> per type to validate

For example this design allows one constraint annotation Size be applied to String, Integer and BigInteger

Constraint Definition Example


@NotNull @Size(min=5,max=9) @Pattern(regexp="[09]{5}|[09]{9}") @ReportAsSingleViolation @Constraint(validatedBy=UsZipcodeValidator.class) @Documented @Target({METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER}) @Retention(RUNTIME) public@interfaceUsZipcode{ Stringmessage()default"Wrongzipcode"; Class<?>[]groups()default{}; Class<?extendsPayload>[]payload()default{}; }

Example Constraint Validation Implementation


publicclassZipCodeValidatorimplementsConstraintValidator<ZipCode,String>{

publicvoidinitialize(ZipCodeconstraint){ }

publicbooleanisValid(Stringvalue,ConstraintValidatorContextcontext){ if(value==null)returntrue; returnfalse; } }

Groups

Groups can be used to selective apply a constraint to a class annotated with Bean Validation annotations. groups() is a required annotation method which can be specified in the class using Bean Validation annotations If a group is not specified javax.validation.groups.Default is the default group

Groups Example

Specificationofgroupswhendefiningconstraints publicclassUser{ @NotNullprivateStringfirstname; @NotNull(groups=Default.class)privateStringlastname; @NotNull(groups={Billable.class,BuyInOneClick.class}) privateCreditCarddefaultCreditCard; }

Selectiveapplicationofgroupswhenvalidatingbean Validatorvalidator= Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<Driver>>violations= validator.validate(driver,Default.class,BuyInOneClick.class);

Cost Analysis

Free to use and modify as per the Apache 2.0 license Allows code to be written once and reused applying the DRY principle Libraries of constraints can be created facilitating reuse that encompassing all the constraints that a particular business uses in conducting its business. (ex. Street Address, State, ZipCode, Credit Card, etc.)

JSR 303 And Struts 1

JSR 303 is domain agnostic and can be adapted to any framework - it can be used in Swing apps JSR 303 can be used in Struts 1 applications with a suitable adapter The open source project sbva, the Struts Bean Validation Adapter allows JSR 303 to be used with Struts 1 applications. The sbva project is hosted at http://sbva.googlecode.com

sbva example

HereisanexampleofhowtovalidateyourStrutsactionform importjavax.validation.constraints.NotNull; importjavax.validation.constraints.Size; importcom.googlecode.sbva.DefaultStrutsBeanValidationAdapter; importcom.mycompany.Minimal; importcom.mycompany.SecondStep; publicclassUserFormextendsActionForm{ privatestaticDefaultStrutsBeanValidationAda ... @NotNull(groups=Minimal.class) @Size(max=50,groups=FirstStep.class)privateStringstreet1; @NotNull(groups=SecondStep.class)privateStringcity; @NotNull(groups={Minimal.class,SecondStep.class}) privateStringzipCode; ... @Override publicActionErrorsvalidate(ActionMappingmapping,HttpServletRequestrequest){ return beanValidationToStrutsConverter.beanValidationErrorsToActionErrors(this,request); } ...

Questions

sbva Demo

Sbva comes with a struts example and its unit test suite

Вам также может понравиться