SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentationHyphen Call
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Sam Brannen
 
Ch07 使用 JSTL
Ch07 使用 JSTLCh07 使用 JSTL
Ch07 使用 JSTLJustin Lin
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaEdureka!
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트Ji-Woong Choi
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataWaheed Nazir
 

Was ist angesagt? (20)

Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring boot
Spring bootSpring boot
Spring boot
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Ch07 使用 JSTL
Ch07 使用 JSTLCh07 使用 JSTL
Ch07 使用 JSTL
 
Servlet
Servlet Servlet
Servlet
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
 

Andere mochten auch

Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data AccessDzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web FlowDzmitry Naskou
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.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 LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteFernando Camargo
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaFernando Camargo
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIFernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf Conference
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02Guo Albert
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseAlexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник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 designJoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designFernando Camargo
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009kensipe
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialRam132
 

Andere mochten auch (20)

Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
 
Design de RESTful APIs
Design de RESTful APIsDesign de RESTful APIs
Design de RESTful APIs
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designJoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered design
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Hibernate
HibernateHibernate
Hibernate
 

Ähnlich wie Spring Framework - Validation

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdfDo it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdfadamsapparelsformen
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
What’s New in Spring Data MongoDB
What’s New in Spring Data MongoDBWhat’s New in Spring Data MongoDB
What’s New in Spring Data MongoDBVMware Tanzu
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScriptMehdi Valikhani
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?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 apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiRaffaele Chiocca
 
Kief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terribleKief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terribleThoughtworks
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...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 KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirWix Engineering
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConqeTimeline, LLC
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USCreating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USAnnyce Davis
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012DefCamp
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...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 ApplicationsJavascript-heavy Salesforce Applications
Javascript-heavy Salesforce ApplicationsSalesforce Developers
 

Ähnlich wie Spring Framework - Validation (20)

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdfDo it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
Do it in Java Please ExamPrep4_Spring2023 Source Packages lo.pdf
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
What’s New in Spring Data MongoDB
What’s New in Spring Data MongoDBWhat’s New in Spring Data MongoDB
What’s New in Spring Data MongoDB
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScript
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
 
Kief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terribleKief Morris - Infrastructure is terrible
Kief Morris - Infrastructure is terrible
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam Katzir
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USCreating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf US
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012
 
Lecture17
Lecture17Lecture17
Lecture17
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
 
Javascript-heavy Salesforce Applications
Javascript-heavy Salesforce ApplicationsJavascript-heavy Salesforce Applications
Javascript-heavy Salesforce Applications
 

Kürzlich hochgeladen

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Kürzlich hochgeladen (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

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