SlideShare a Scribd company logo
Spring Framework - Validation




                SPRING FRAMEWORK 3.0
Dmitry Noskov   Validation, JSR-303
Spring Validation




          Spring Framework - Validation   Dmitry Noskov
Spring Validator
public interface Validator {


    /** Can this instances of the supplied clazz */
    boolean supports(Class<?> clazz);


    /**
    * Validate the supplied target object, which must be
    * @param target the object that is to be validated
    * @param errors contextual state about the validation process
    */
    void validate(Object target, Errors errors);
}



                           Spring Framework - Validation   Dmitry Noskov
Simple Spring validator
public class MakeValidator implements Validator {
    public boolean supports(Class<?> c) {return Make.class.equals(c);}


    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "name", "er.required");
        Make make = (Make)target;


        if (make.getName().length()<3) {
            errors.rejectValue("name", "er.minlength");
        } else if (make.getName().length()>20) {
            errors.rejectValue("name", "er.maxlength");
        }
    }
}

                                Spring Framework - Validation   Dmitry Noskov
Auxiliary classes
   Errors
     reject
     rejectValue



   ValidationUtils
     rejectIfEmpty
     rejectIfEmptyOrWhitespace

     invokeValidator



                      Spring Framework - Validation   Dmitry Noskov
Resolving codes
   will create message codes for an object error
     code + "." + object name
     code

   will create message codes for a field
     code + "." + object name + "." + field
     code + "." + field

     code + "." + field type

     code



                        Spring Framework - Validation   Dmitry Noskov
JSR-303
a specification for Bean Validation




                Spring Framework - Validation   Dmitry Noskov
Old validation solution




              Spring Framework - Validation   Dmitry Noskov
DDD with JSR-303




           Spring Framework - Validation   Dmitry Noskov
Fundamentals

                        Annotation




                                                 Constraint
       Message        Validator                  Validator




                        Constraint
                        Violation



                 Spring Framework - Validation     Dmitry Noskov
Constraints
   applicable to class, method, field
   custom constraints
   composition
   object graphs
   properties:
     message
     groups

     payload



                       Spring Framework - Validation   Dmitry Noskov
Standard constraints
Annotation       Type                      Description
@Min(10)         Number                    must be higher or equal
@Max(10)         Number                    must be lower or equal
@AssertTrue      Boolean                   must be true, null is valid
@AssertFalse     Boolean                   must be false, null is valid
@NotNull         any                       must not be null
@NotEmpty        String / Collection’s     must be not null or empty
@NotBlank        String                    @NotEmpty and whitespaces ignored
@Size(min,max)   String / Collection’s     must be between boundaries
@Past            Date / Calendar           must be in the past
@Future          Date / Calendar           must be in the future
@Pattern         String                    must math the regular expression

                           Spring Framework - Validation   Dmitry Noskov
Example

public class Make {


    @Size(min = 3, max = 20)
    private String name;


    @Size(max = 200)
    private String description;
}




                           Spring Framework - Validation   Dmitry Noskov
Validator methods

public interface Validator {
     /** Validates all constraints on object. */
     validate(T object, Class<?>... groups)


     /** Validates all constraints placed on the property of object
*/
     validateProperty(T object, String pName, Class<?>... groups)


     /** Validates all constraints placed on the property
     * of the class beanType would the property value */
  validateValue(Class<T> type, String pName, Object val,
Class<?>…)
}

                            Spring Framework - Validation   Dmitry Noskov
ConstraintViolation
   exposes constraint violation context
   core methods
     getMessage
     getRootBean

     getLeafBean

     getPropertyPath

     getInvalidValue




                        Spring Framework - Validation   Dmitry Noskov
Validating groups
   separate validating
   simple interfaces for grouping
   inheritance by standard java inheritance
   composition
   combining by @GroupSequence




                      Spring Framework - Validation   Dmitry Noskov
Grouping(1)
   grouping interface
    public interface MandatoryFieldCheck {
    }

   using
    public class Car {
        @Size(min = 3, max = 20, groups = MandatoryFieldCheck.class)
        private String name;


        @Size(max = 20)
        private String color;
    }




                               Spring Framework - Validation   Dmitry Noskov
Grouping(2)
   grouping sequence
    @GroupSequence(Default.class, MandatoryFieldCheck.class)
    public interface CarChecks {
    }

   using
    javax.validation.Validator validator;
    validator.validate(make, CarChecks.class);




                          Spring Framework - Validation   Dmitry Noskov
Composition
   annotation
    @NotNull
    @CapitalLetter
    @Size(min = 2, max = 14)
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ METHOD, FIELD, ANNOTATION_TYPE })
    public @interface CarNameConstraint {
    }

   using
    @CarNameConstraint
    private String name;


                           Spring Framework - Validation   Dmitry Noskov
Custom constraint
   create annotation
@Constraint(validatedBy=CapitalLetterValidator.class)
public @interface CapitalLetter {
    String message() default "{carbase.error.capital}";

   implement constraint validator
public class CapitalLetterValidator implements
               ConstraintValidator<CapitalLetter, String> {

   define a default error message
carbase.error.capital=The name must begin with a capital letter




                           Spring Framework - Validation   Dmitry Noskov
LocalValidatorFactoryBean


     Spring                               JSR-303
    Validator                             Validator

             Spring
            Adapter
                Spring Framework - Validation   Dmitry Noskov
Configuration
    define bean
     <bean id="validator"

class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
or
     <mvc:annotation-driven/>

    injecting
     @Autowired
     private javax.validation.Validator validator;
or
     @Autowired
     private org.springframework.validation.Validator validator;


                               Spring Framework - Validation   Dmitry Noskov
Information
   JSR-303 reference
       http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/
       http://static.springsource.org/spring/docs/3.0.x/spring-framework-
        reference/html/validation.html
   samples
       http://src.springsource.org/svn/spring-samples/mvc-showcase
   blog
       http://blog.springsource.com/category/web/
   forum
       http://forum.springsource.org/forumdisplay.php?f=25

                              Spring Framework - Validation   Dmitry Noskov
Questions




            Spring Framework - Validation   Dmitry Noskov
The end




             http://www.linkedin.com/in/noskovd

      http://www.slideshare.net/analizator/presentations
Ad

Recommended

Spring boot
Spring boot
Gyanendra Yadav
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
Node.js Express
Node.js Express
Eyal Vardi
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul
 
Spring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Spring Core
Spring Core
Pushan Bhattacharya
 
ReactJS presentation
ReactJS presentation
Thanh Tuong
 
Reactjs
Reactjs
Mallikarjuna G D
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c# .net version f8
ENSET, Université Hassan II Casablanca
 
Maven Introduction
Maven Introduction
Sandeep Chawla
 
Spring Boot
Spring Boot
Jaran Flaath
 
Spring boot
Spring boot
Pradeep Shanmugam
 
Reactjs
Reactjs
Neha Sharma
 
Spring Framework - Spring Security
Spring Framework - Spring Security
Dzmitry Naskou
 
Spring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring Boot
Spring Boot
Jaydeep Kale
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Introduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Framework
valuebound
 
React state
React state
Ducat
 
JDBC
JDBC
People Strategists
 
Namespaces in C#
Namespaces in C#
yogita kachve
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
ANKUSH CHAVAN
 
ReactJS
ReactJS
Ram Murat Sharma
 
jQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
React js
React js
Oswald Campesato
 
Spring Framework - Expression Language
Spring Framework - Expression Language
Dzmitry Naskou
 
Spring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 

More Related Content

What's hot (20)

Reactjs
Reactjs
Mallikarjuna G D
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c# .net version f8
ENSET, Université Hassan II Casablanca
 
Maven Introduction
Maven Introduction
Sandeep Chawla
 
Spring Boot
Spring Boot
Jaran Flaath
 
Spring boot
Spring boot
Pradeep Shanmugam
 
Reactjs
Reactjs
Neha Sharma
 
Spring Framework - Spring Security
Spring Framework - Spring Security
Dzmitry Naskou
 
Spring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring Boot
Spring Boot
Jaydeep Kale
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Introduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Framework
valuebound
 
React state
React state
Ducat
 
JDBC
JDBC
People Strategists
 
Namespaces in C#
Namespaces in C#
yogita kachve
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
ANKUSH CHAVAN
 
ReactJS
ReactJS
Ram Murat Sharma
 
jQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
React js
React js
Oswald Campesato
 

Viewers also liked (20)

Spring Framework - Expression Language
Spring Framework - Expression Language
Dzmitry Naskou
 
Spring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Spring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web Flow
Dzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.
IT Weekend
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
Fernando Camargo
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
Fernando Camargo
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
Fernando Camargo
 
Design de RESTful APIs
Design de RESTful APIs
Fernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf Conference
 
Spring bean mod02
Spring bean mod02
Guo Albert
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
Alexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
Alina Dolgikh
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered design
Fernando Camargo
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
Er. Gaurav Kumar
 
Spring MVC
Spring MVC
Aaron Schram
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC CodeMash 2009
kensipe
 
Hibernate Tutorial
Hibernate Tutorial
Ram132
 
Hibernate
Hibernate
Prashant Kalkar
 
Spring Framework - Expression Language
Spring Framework - Expression Language
Dzmitry Naskou
 
Spring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Spring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web Flow
Dzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.
IT Weekend
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
Fernando Camargo
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
Fernando Camargo
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
Fernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf Conference
 
Spring bean mod02
Spring bean mod02
Guo Albert
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
Alexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
Alina Dolgikh
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered design
Fernando Camargo
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
Er. Gaurav Kumar
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC CodeMash 2009
kensipe
 
Hibernate Tutorial
Hibernate Tutorial
Ram132
 
Ad

Similar to Spring Framework - Validation (20)

Spring 3: What's New
Spring 3: What's New
Ted Pennings
 
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
adamsapparelsformen
 
Unit test candidate solutions
Unit test candidate solutions
benewu
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
What’s New in Spring Data MongoDB
What’s New in Spring Data MongoDB
VMware Tanzu
 
Metaprogramming in JavaScript
Metaprogramming in JavaScript
Mehdi Valikhani
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?
sscalabrino
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
Raffaele Chiocca
 
Kief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terrible
Thoughtworks
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Xlator
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam Katzir
Wix Engineering
 
Data Types/Structures in DivConq
Data Types/Structures in DivConq
eTimeline, LLC
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
Bastian Feder
 
Nestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf US
Annyce Davis
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012
DefCamp
 
Lecture17
Lecture17
vantinhkhuc
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Stefan Marr
 
Javascript-heavy Salesforce Applications
Javascript-heavy Salesforce Applications
Salesforce Developers
 
Spring 3: What's New
Spring 3: What's New
Ted Pennings
 
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
adamsapparelsformen
 
Unit test candidate solutions
Unit test candidate solutions
benewu
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
What’s New in Spring Data MongoDB
What’s New in Spring Data MongoDB
VMware Tanzu
 
Metaprogramming in JavaScript
Metaprogramming in JavaScript
Mehdi Valikhani
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?
sscalabrino
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
Raffaele Chiocca
 
Kief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terrible
Thoughtworks
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Xlator
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam Katzir
Wix Engineering
 
Data Types/Structures in DivConq
Data Types/Structures in DivConq
eTimeline, LLC
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
Bastian Feder
 
Nestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf US
Annyce Davis
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012
DefCamp
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Stefan Marr
 
Javascript-heavy Salesforce Applications
Javascript-heavy Salesforce Applications
Salesforce Developers
 
Ad

Recently uploaded (20)

TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 

Spring Framework - Validation

  • 1. Spring Framework - Validation SPRING FRAMEWORK 3.0 Dmitry Noskov Validation, JSR-303
  • 2. Spring Validation Spring Framework - Validation Dmitry Noskov
  • 3. Spring Validator public interface Validator { /** Can this instances of the supplied clazz */ boolean supports(Class<?> clazz); /** * Validate the supplied target object, which must be * @param target the object that is to be validated * @param errors contextual state about the validation process */ void validate(Object target, Errors errors); } Spring Framework - Validation Dmitry Noskov
  • 4. Simple Spring validator public class MakeValidator implements Validator { public boolean supports(Class<?> c) {return Make.class.equals(c);} public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "name", "er.required"); Make make = (Make)target; if (make.getName().length()<3) { errors.rejectValue("name", "er.minlength"); } else if (make.getName().length()>20) { errors.rejectValue("name", "er.maxlength"); } } } Spring Framework - Validation Dmitry Noskov
  • 5. Auxiliary classes  Errors  reject  rejectValue  ValidationUtils  rejectIfEmpty  rejectIfEmptyOrWhitespace  invokeValidator Spring Framework - Validation Dmitry Noskov
  • 6. Resolving codes  will create message codes for an object error  code + "." + object name  code  will create message codes for a field  code + "." + object name + "." + field  code + "." + field  code + "." + field type  code Spring Framework - Validation Dmitry Noskov
  • 7. JSR-303 a specification for Bean Validation Spring Framework - Validation Dmitry Noskov
  • 8. Old validation solution Spring Framework - Validation Dmitry Noskov
  • 9. DDD with JSR-303 Spring Framework - Validation Dmitry Noskov
  • 10. Fundamentals Annotation Constraint Message Validator Validator Constraint Violation Spring Framework - Validation Dmitry Noskov
  • 11. Constraints  applicable to class, method, field  custom constraints  composition  object graphs  properties:  message  groups  payload Spring Framework - Validation Dmitry Noskov
  • 12. Standard constraints Annotation Type Description @Min(10) Number must be higher or equal @Max(10) Number must be lower or equal @AssertTrue Boolean must be true, null is valid @AssertFalse Boolean must be false, null is valid @NotNull any must not be null @NotEmpty String / Collection’s must be not null or empty @NotBlank String @NotEmpty and whitespaces ignored @Size(min,max) String / Collection’s must be between boundaries @Past Date / Calendar must be in the past @Future Date / Calendar must be in the future @Pattern String must math the regular expression Spring Framework - Validation Dmitry Noskov
  • 13. Example public class Make { @Size(min = 3, max = 20) private String name; @Size(max = 200) private String description; } Spring Framework - Validation Dmitry Noskov
  • 14. Validator methods public interface Validator { /** Validates all constraints on object. */ validate(T object, Class<?>... groups) /** Validates all constraints placed on the property of object */ validateProperty(T object, String pName, Class<?>... groups) /** Validates all constraints placed on the property * of the class beanType would the property value */ validateValue(Class<T> type, String pName, Object val, Class<?>…) } Spring Framework - Validation Dmitry Noskov
  • 15. ConstraintViolation  exposes constraint violation context  core methods  getMessage  getRootBean  getLeafBean  getPropertyPath  getInvalidValue Spring Framework - Validation Dmitry Noskov
  • 16. Validating groups  separate validating  simple interfaces for grouping  inheritance by standard java inheritance  composition  combining by @GroupSequence Spring Framework - Validation Dmitry Noskov
  • 17. Grouping(1)  grouping interface public interface MandatoryFieldCheck { }  using public class Car { @Size(min = 3, max = 20, groups = MandatoryFieldCheck.class) private String name; @Size(max = 20) private String color; } Spring Framework - Validation Dmitry Noskov
  • 18. Grouping(2)  grouping sequence @GroupSequence(Default.class, MandatoryFieldCheck.class) public interface CarChecks { }  using javax.validation.Validator validator; validator.validate(make, CarChecks.class); Spring Framework - Validation Dmitry Noskov
  • 19. Composition  annotation @NotNull @CapitalLetter @Size(min = 2, max = 14) @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ METHOD, FIELD, ANNOTATION_TYPE }) public @interface CarNameConstraint { }  using @CarNameConstraint private String name; Spring Framework - Validation Dmitry Noskov
  • 20. Custom constraint  create annotation @Constraint(validatedBy=CapitalLetterValidator.class) public @interface CapitalLetter { String message() default "{carbase.error.capital}";  implement constraint validator public class CapitalLetterValidator implements ConstraintValidator<CapitalLetter, String> {  define a default error message carbase.error.capital=The name must begin with a capital letter Spring Framework - Validation Dmitry Noskov
  • 21. LocalValidatorFactoryBean Spring JSR-303 Validator Validator Spring Adapter Spring Framework - Validation Dmitry Noskov
  • 22. Configuration  define bean <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> or <mvc:annotation-driven/>  injecting @Autowired private javax.validation.Validator validator; or @Autowired private org.springframework.validation.Validator validator; Spring Framework - Validation Dmitry Noskov
  • 23. Information  JSR-303 reference  http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/validation.html  samples  http://src.springsource.org/svn/spring-samples/mvc-showcase  blog  http://blog.springsource.com/category/web/  forum  http://forum.springsource.org/forumdisplay.php?f=25 Spring Framework - Validation Dmitry Noskov
  • 24. Questions Spring Framework - Validation Dmitry Noskov
  • 25. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations