SlideShare una empresa de Scribd logo
1 de 86
© http://philowendeltreppe.wordpress.com/




GEPRÜFTE BOHNE
 Der Bean Validation Standard
       Sandro Sonntag
              1                     Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA




                                                                            © delater / PIXELIO

Der Bean Validation Standard JSR 303     2      Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit




                                                                            © delater / PIXELIO

Der Bean Validation Standard JSR 303     2      Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit

• Existierende               Lösungen




                                                                            © delater / PIXELIO

Der Bean Validation Standard JSR 303     2      Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit

• Existierende               Lösungen

• Der       JSR 303




                                                                            © delater / PIXELIO

Der Bean Validation Standard JSR 303     2      Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit

• Existierende               Lösungen

• Der       JSR 303

• JSR      303 Implementierungen



                                                                            © delater / PIXELIO

Der Bean Validation Standard JSR 303     2      Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit           • Constraints   Deklarieren

• Existierende               Lösungen

• Der       JSR 303

• JSR      303 Implementierungen



                                                                                  © delater / PIXELIO

Der Bean Validation Standard JSR 303     2            Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit           • Constraints   Deklarieren

• Existierende               Lösungen        • Gruppierungen

• Der       JSR 303

• JSR      303 Implementierungen



                                                                                  © delater / PIXELIO

Der Bean Validation Standard JSR 303     2            Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit           • Constraints   Deklarieren

• Existierende               Lösungen        • Gruppierungen

• Der       JSR 303                          • Messages

• JSR      303 Implementierungen



                                                                                  © delater / PIXELIO

Der Bean Validation Standard JSR 303     2            Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit           • Constraints     Deklarieren

• Existierende               Lösungen        • Gruppierungen

• Der       JSR 303                          • Messages

• JSR      303 Implementierungen             • Eigene   Constraints



                                                                                    © delater / PIXELIO

Der Bean Validation Standard JSR 303     2              Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Bedarf         und Notwendigkeit           • Constraints     Deklarieren

• Existierende               Lösungen        • Gruppierungen

• Der       JSR 303                          • Messages

• JSR      303 Implementierungen             • Eigene   Constraints

                                             • Metadaten      lesen

                                                                                    © delater / PIXELIO

Der Bean Validation Standard JSR 303     2              Sandro Sonntag © Adorsys GmbH & Co KG
WARUM VALIDIERUNG?




                                                              © Ernst Rose / PIXELIO




Der Bean Validation Standard JSR 303   3   Sandro Sonntag © Adorsys GmbH & Co KG
WARUM VALIDIERUNG?
•   Validierung

    •   Prüfung von Thesen

    •   Sicherstellung der Datenqualität

    •   Misstrauen des Nutzers

    •   Prävention zur Vermeidung von Fehlern



                                                                       © Ernst Rose / PIXELIO




Der Bean Validation Standard JSR 303            3   Sandro Sonntag © Adorsys GmbH & Co KG
WARUM VALIDIERUNG?
•   Validierung

    •   Prüfung von Thesen

    •   Sicherstellung der Datenqualität

    •   Misstrauen des Nutzers

    •   Prävention zur Vermeidung von Fehlern

•   Sicherheits-Belange

    •   Constraints                                                    © Ernst Rose / PIXELIO


    •   Regeln der Prüfung

    •   NotNull, Min, Max, Length
Der Bean Validation Standard JSR 303            3   Sandro Sonntag © Adorsys GmbH & Co KG
Webservice         Browser         Richclient

                Java Application

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient   Java

                Java Application

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient   Java

                Java Application

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient   Java

                Java Application

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient   Java

                Java Application

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib


                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib

                                                 WSDL
                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib

                                                 WSDL
                    RDBM



  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib

                                                 WSDL
                    RDBM
                                                  DDL


  CONSTRAINTS IN TIERS
                              4
Webservice         Browser         Richclient      Java

                Java Application                JavaScript

 Präsentation      Business        DAO            Taglib

                                                 WSDL
                    RDBM
                                                  DDL


  CONSTRAINTS IN TIERS
                              4
Webservice          Browser           Richclient      Java

                    Java Application                  JavaScript

     Präsentation      Business          DAO            Taglib

                                                       WSDL
                        RDBM
                                                        DDL


       CONSTRAINTS IN TIERS
•Gleiche Prüfungen über alle Schichten
•(meist) ein Model
                                  4
AKTUELLE LÖSUNGEN
                                         Java Server Faces

              <h:inputText id="firstName" value="#{UserRegistration.user.firstName}">
                  <f:validateLength minimum="2" maximum="25" />
              </h:inputText>




                public void validateEmail(FacesContext context, UIComponent toValidate,
                        Object value) {
                    String email = (String) value;

                      if (email.indexOf('@') == -1) {
                          ((UIInput) toValidate).setValid(false);

                           FacesMessage message = new FacesMessage("Invalid Email");
                           context.addMessage(toValidate.getClientId(context), message);
                      }
                }

Der Bean Validation Standard JSR 303                   5                 Sandro Sonntag © Adorsys GmbH & Co KG
POJO & DDL
           public void check(Address a) {
           	 if (a.getStreet() == null || a.getStreet().length() > 60) {
           	 	 throw new ValidationException("Street has not a valid value!");
           	 }
           }




Der Bean Validation Standard JSR 303         6              Sandro Sonntag © Adorsys GmbH & Co KG
POJO & DDL
           public void check(Address a) {
           	 if (a.getStreet() == null || a.getStreet().length() > 60) {
           	 	 throw new ValidationException("Street has not a valid value!");
           	 }
           }




            create table LOGIN (
            	 id bigint not null auto_increment,
            	 login varchar(255) not null,
            	 name varchar(255) not null,
            	 password varchar(255) not null,
            	 primary key (id));


Der Bean Validation Standard JSR 303         6              Sandro Sonntag © Adorsys GmbH & Co KG
NACHTEILE


• Layerspezifische Validierungs Technologien

• Code          Duplizierung

• Inkonsistenz

• Verstreuung                über den Code

Der Bean Validation Standard JSR 303         7   Sandro Sonntag © Adorsys GmbH & Co KG
BESSER WÄHRE DOCH




                                                                  © Ernst Rose / PIXELIO

Der Bean Validation Standard JSR 303   8   Sandro Sonntag © Adorsys GmbH & Co KG
BESSER WÄHRE DOCH

•   Einheitliche Deklaration der Constaints

    • In    einer Sprache

    • Layer        agnostisch




                                                                     © Ernst Rose / PIXELIO

Der Bean Validation Standard JSR 303   8      Sandro Sonntag © Adorsys GmbH & Co KG
BESSER WÄHRE DOCH

•   Einheitliche Deklaration der Constaints

    • In    einer Sprache

    • Layer        agnostisch

•   Validierung der Constraints

    • Durch          wiederverwendbares API

    • In    allen Schichten verwendbar
                                                                     © Ernst Rose / PIXELIO

Der Bean Validation Standard JSR 303   8      Sandro Sonntag © Adorsys GmbH & Co KG
DEKLARATION




Der Bean Validation Standard JSR 303   9   Sandro Sonntag © Adorsys GmbH & Co KG
DEKLARATION

• Javadoc          → Liest niemand




Der Bean Validation Standard JSR 303   9   Sandro Sonntag © Adorsys GmbH & Co KG
DEKLARATION

• Javadoc          → Liest niemand

• XML         Konfiguration → zu weit vom Code




Der Bean Validation Standard JSR 303   9    Sandro Sonntag © Adorsys GmbH & Co KG
DEKLARATION

• Javadoc          → Liest niemand

• XML         Konfiguration → zu weit vom Code

• Taglib       → Layer spezifisch




Der Bean Validation Standard JSR 303   9    Sandro Sonntag © Adorsys GmbH & Co KG
DEKLARATION

• Javadoc          → Liest niemand

• XML         Konfiguration → zu weit vom Code

• Taglib       → Layer spezifisch

•   @Annotation

    →Dicht          am Code

    →Java!
Der Bean Validation Standard JSR 303   9    Sandro Sonntag © Adorsys GmbH & Co KG
FRAMEWORKS HEUTE




Der Bean Validation Standard JSR 303   10   Sandro Sonntag © Adorsys GmbH & Co KG
FRAMEWORKS HEUTE

• Apache            Commons Validator

• JSF Validator

• Xwork

• Hibernate Validator

• MyFaces Validation


Der Bean Validation Standard JSR 303    10   Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303




Der Bean Validation Standard JSR 303   11   Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303
•   Standardisieren von
    Constraints

    • Annotations
    • Implementierung                  eigener
       Constraints




Der Bean Validation Standard JSR 303             11   Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303
•   Standardisieren von
    Constraints

    • Annotations
    • Implementierung                  eigener
       Constraints

•   Validierungs API

    • Layerunabhängig
    • I18n
    • Extension Points
Der Bean Validation Standard JSR 303             11   Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303
•   Standardisieren von                               •   Standardisierung der
    Constraints                                           Metadata API

    • Annotations
    • Implementierung                  eigener
       Constraints

•   Validierungs API

    • Layerunabhängig
    • I18n
    • Extension Points
Der Bean Validation Standard JSR 303             11              Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303
•   Standardisieren von                               •   Standardisierung der
    Constraints                                           Metadata API

    • Annotations                                     •   Integration anderer
    • Implementierung                  eigener            Frameworks
       Constraints

•   Validierungs API

    • Layerunabhängig
    • I18n
    • Extension Points
Der Bean Validation Standard JSR 303             11              Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303
•   Standardisieren von                               •   Standardisierung der
    Constraints                                           Metadata API

    • Annotations                                     •   Integration anderer
    • Implementierung                  eigener            Frameworks
       Constraints
                                                      •   XML Konfiguration
•   Validierungs API

    • Layerunabhängig
    • I18n
    • Extension Points
Der Bean Validation Standard JSR 303             11              Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303




Der Bean Validation Standard JSR 303      12     Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303

•   Status

    •   Proposed Final Draft (30 März, 2009)

    •   RI in Glassfish V3




Der Bean Validation Standard JSR 303      12     Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303

•   Status

    •   Proposed Final Draft (30 März, 2009)

    •   RI in Glassfish V3

•   Spec Lead: Emmanuel Bernard




Der Bean Validation Standard JSR 303      12     Sandro Sonntag © Adorsys GmbH & Co KG
JSR 303

•   Status

    •   Proposed Final Draft (30 März, 2009)

    •   RI in Glassfish V3

•   Spec Lead: Emmanuel Bernard

•   Implementierungen

    •   Hibernate Validator (RI)

    •   Agimatec Validation
Der Bean Validation Standard JSR 303      12     Sandro Sonntag © Adorsys GmbH & Co KG
AGENDA

• Constraints              Deklarieren

• Gruppierungen

• Messages

• Eigene         Constraints

• Metadaten               lesen

Der Bean Validation Standard JSR 303     13     Sandro Sonntag © Adorsys GmbH & Co KG
CONSTRAINTS DEKLARIEREN

•   Basierend auf Java Annotations

    •   Class, Getter, Setter
                                            @NotNull
                                            private String firstname;
    •   Kreuzplausibilisierungen

•   Anpassbarkeit

    •   Gruppen                             @Valid
                                            @NotNull(groups = First.class)
                                            private Author author;
    •   Messages

    •   Eigene Parameter
Der Bean Validation Standard JSR 303   14           Sandro Sonntag © Adorsys GmbH & Co KG
public class Person {

      @NotEmpty
      @NotNull
      private String firstname;

      @NotEmpty
      @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}")
      private String lastname;

      @NotNull
      @Valid
      private Address address;

      public String getFirstname() {
          return firstname;
      }

      public void setFirstname(String firstname) {
          this.firstname = firstname;
      }

      public String getLastname() {
          return lastname;
      }

      public void setLastname(String lastname) {
          this.lastname = lastname;
      }

      public Address getAddress() {
          return address;
      }

      public void setAddress(Address address) {
          this.address = address;
      }

Der Bean Validation Standard JSR 303
  }                                                    15                   Sandro Sonntag © Adorsys GmbH & Co KG
ANNOTATIONS
Der Bean Validation Standard JSR 303   16   Sandro Sonntag © Adorsys GmbH & Co KG
•Logik                                •Fachlich
       •@NotNull                             •@Email
       •@NotEmpty                            •@EAN
       •@AssertTrue / False                  •@CreditCard
      •Wertebereich                         •Andere
       •@Min                                 •@Valid
       •@Max                                 •@Pattern
       •@Digits
       •@Size
                               ANNOTATIONS
Der Bean Validation Standard JSR 303   16        Sandro Sonntag © Adorsys GmbH & Co KG
NÜTZLICHE DINGE

•   Muilti Constraints

    •   @Patterns({@Pattern(regexp=“???“)})

•   Vererbung

    •   Superclass

    •   Interface

    •   Additiv

•   Collections, Maps, Arrays
Der Bean Validation Standard JSR 303   17     Sandro Sonntag © Adorsys GmbH & Co KG
VALIDATION API
                  Validieren einer Bean
                     Set<InvalidConstraint> errors = addressValidator.validate(address);




                  Eines Properties
                     validator.validateProperty(address, "city")




                  Eines Wertes
                     validator.validateValue(Address.class, "city", "Paris")


Der Bean Validation Standard JSR 303             18                Sandro Sonntag © Adorsys GmbH & Co KG
VALIDATION API
• Validierungsergebnis
                    ConstraintViolationImpl{
                        rootBean=org.adorsys.demo.validation.validategraph.Person@287811,
                        propertyPath='lastname',
                        message='The size of lastname must be between 3 and 30',
                        leafBean=org.adorsys.demo.validation.validategraph.Person@287811,
                        value=Sa}



    •   Fehlgeschlagene Constraints

    •   Ungültiger Wert

    •   Fehlermeldung (i18n)

    •   Bean Instanz


Der Bean Validation Standard JSR 303                 19                Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES
•   Constraint




Der Bean Validation Standard JSR 303      20      Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES
•   Constraint
    • Definiert             eine Default Message
         public @interface Max {
         	 String message() default "{validator.max}";
         ...




Der Bean Validation Standard JSR 303         20          Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES
•   Constraint
    • Definiert             eine Default Message
         public @interface Max {
         	 String message() default "{validator.max}";
         ...

    • Kann        überschrieben werden
         @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}")
         	 private String lastname;




Der Bean Validation Standard JSR 303          20              Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES
•   Constraint
    • Definiert             eine Default Message
         public @interface Max {
         	 String message() default "{validator.max}";
         ...

    • Kann        überschrieben werden
         @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}")
         	 private String lastname;


    • Kann        programmatisch erstellt werden
           constraintValidatorContext.disableDefaultError();
           constraintValidatorContext.addError("A programmatic error");


Der Bean Validation Standard JSR 303          20               Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES




Der Bean Validation Standard JSR 303      21      Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES

•   Parameter Ersetzung

    • Constraint              Parameter nutzbar
        •   Value must be between {min} and {max}




Der Bean Validation Standard JSR 303         21     Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES

•   Parameter Ersetzung

    • Constraint              Parameter nutzbar
        •   Value must be between {min} and {max}

•   Externalizierbar

    • I18n       Resource Bundle
        •   ValidationMessages.properties




Der Bean Validation Standard JSR 303         21     Sandro Sonntag © Adorsys GmbH & Co KG
MESSAGES

•   Parameter Ersetzung

    • Constraint              Parameter nutzbar
        •   Value must be between {min} and {max}

•   Externalizierbar

    • I18n       Resource Bundle
        •   ValidationMessages.properties

•   MessageInterpolator austauschbar
Der Bean Validation Standard JSR 303         21     Sandro Sonntag © Adorsys GmbH & Co KG
GRUPPIERUNG VON
                        CONSTRAINTS




                                                                   © staumichel / PIXELIO




Der Bean Validation Standard JSR 303   22   Sandro Sonntag © Adorsys GmbH & Co KG
GRUPPIERUNG VON
                        CONSTRAINTS
•   Validierung eines Subsets von Constraints

    •   Aktivierung von mehreren Gruppen möglich
    •   Portionsweise Validierung in Prozessen/Wizards




                                                                          © staumichel / PIXELIO




Der Bean Validation Standard JSR 303   22          Sandro Sonntag © Adorsys GmbH & Co KG
GRUPPIERUNG VON
                        CONSTRAINTS
•   Validierung eines Subsets von Constraints

    •   Aktivierung von mehreren Gruppen möglich
    •   Portionsweise Validierung in Prozessen/Wizards
•   Implementierung

    •   Group = Interface
    •   Vererbung von Gruppen durch „extends“
    •   Standard Gruppe = Default                                         © staumichel / PIXELIO




Der Bean Validation Standard JSR 303   22          Sandro Sonntag © Adorsys GmbH & Co KG
GRUPPIERUNG VON
                        CONSTRAINTS
•   Validierung eines Subsets von Constraints

    •   Aktivierung von mehreren Gruppen möglich
    •   Portionsweise Validierung in Prozessen/Wizards
•   Implementierung

    •   Group = Interface
    •   Vererbung von Gruppen durch „extends“
    •   Standard Gruppe = Default                                         © staumichel / PIXELIO




•   GroupSequences zur Priorisierung möglich
Der Bean Validation Standard JSR 303   22          Sandro Sonntag © Adorsys GmbH & Co KG
@ValidAddress(groups=Address.AddressCheck.class)
                           @GroupSequence({Address.Basic.class, Address.AddressCheck.class})
                           public class Address {

                                /**
                                 * check the Address only if the default group is valid
                                 */
                                public interface AddressCheck {}

                                public interface Basic {}

                                @NotEmpty(groups=Basic.class)
                                @NotNull(groups=Basic.class)
                                private String address;

                                @NotEmpty(groups=Basic.class)
                                @NotNull(groups=Basic.class)
                                private String zip;

                                @NotEmpty(groups=Basic.class)
                                @NotNull(groups=Basic.class)
                                private String city;

                                public String getAddress() {
                                    return address;
                                }

                                ...

                           }



Der Bean Validation Standard JSR 303                        23                  Sandro Sonntag © Adorsys GmbH & Co KG
CUSTOM CONSTAINTS




Der Bean Validation Standard JSR 303   24   Sandro Sonntag © Adorsys GmbH & Co KG
CUSTOM CONSTAINTS
                                       @Constraint(validatedBy = NumericValidator.class)
                                       @Target({ElementType.FIELD, ElementType.METHOD})
                                       @Retention(RUNTIME)
• Eine Annotation                      public @interface Numeric {

                                       	   String message() default "not a numeric value";
                                       	   Class<?>[] groups() default { };

                                       }




Der Bean Validation Standard JSR 303                     24                  Sandro Sonntag © Adorsys GmbH & Co KG
CUSTOM CONSTAINTS
                                       @Constraint(validatedBy = NumericValidator.class)
                                       @Target({ElementType.FIELD, ElementType.METHOD})
                                       @Retention(RUNTIME)
• Eine Annotation                      public @interface Numeric {

                                       	   String message() default "not a numeric value";
                                       	   Class<?>[] groups() default { };

                                       }




                                       public class NumericValidator implements ConstraintValidator<Numeric,
                                       String>{

                                       	   public void initialize(Numeric constraintAnnotation) {
                                       	   }


• Ein Validator
                                       	   public boolean isValid(String numeric,
                                       	   	   	   ConstraintValidatorContext constraintValidatorContext) {
                                       	   	   try {
                                       	   	   	   Long.valueOf(numeric);
                                       	   	   } catch (NumberFormatException e) {
                                       	   	   	   return false;
                                       	   	   }
                                       	   	   return true;
                                       	   }
                                       }
Der Bean Validation Standard JSR 303                     24                  Sandro Sonntag © Adorsys GmbH & Co KG
CUSTOM CONSTAINTS

                             @Numeric(message="A zip has to be numeric.")
                             @Size(min=5, max=5, message="A zip must has a size of 5 digits.")
                             @Constraint(validatedBy={GermanZipcodeValidator.class})
                             @Target({ElementType.FIELD, ElementType.METHOD})
                             @Retention(RUNTIME)
                             public @interface GermanZip {
                                 Class<?>[] groups() default { };

                             }




Der Bean Validation Standard JSR 303                      25                   Sandro Sonntag © Adorsys GmbH & Co KG
COMPOSITE CONSTRAINTS

• Baukasten

• Codeduplizierung

• Wiederverwendung      von
   primitiven Constraints
                                                              © RainerSturm / PIXELIO



• Bessere Toolunterstützung
   durch Verwendung von Core
   Constaints
Der Bean Validation Standard JSR 303   26   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE FEATURES




Der Bean Validation Standard JSR 303   27   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE FEATURES
•   Parameter Override




Der Bean Validation Standard JSR 303   27   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE FEATURES
•   Parameter Override             @Size
                                   @Constraint(validatedBy = FrenchZipcodeValidator.class)
                                   public @interface FrenchZipcode {
                                      String message() default "Wrong zipcode";
                                      @OverridesParameter(constraint=Size.class, parameter="message")
                                      String sizeMessage() default "{beancheck.zipcode.size}";
                                   }




Der Bean Validation Standard JSR 303                       27                   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE FEATURES
•   Parameter Override             @Size
                                   @Constraint(validatedBy = FrenchZipcodeValidator.class)
                                   public @interface FrenchZipcode {
                                      String message() default "Wrong zipcode";
                                      @OverridesParameter(constraint=Size.class, parameter="message")
                                      String sizeMessage() default "{beancheck.zipcode.size}";
                                   }



•   Ein Constraint mehre Validatoren

    •   @Constraint(validatedBy={SizeValidatorForCollection.class})




Der Bean Validation Standard JSR 303                       27                   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE FEATURES
•   Parameter Override             @Size
                                   @Constraint(validatedBy = FrenchZipcodeValidator.class)
                                   public @interface FrenchZipcode {
                                      String message() default "Wrong zipcode";
                                      @OverridesParameter(constraint=Size.class, parameter="message")
                                      String sizeMessage() default "{beancheck.zipcode.size}";
                                   }



•   Ein Constraint mehre Validatoren

    •   @Constraint(validatedBy={SizeValidatorForCollection.class})

•   Konfigurative Zuordnung

    •   Trennung von Deklaration und Implementierung



Der Bean Validation Standard JSR 303                       27                   Sandro Sonntag © Adorsys GmbH & Co KG
METADATEN API
•   Zugiff auf das Constraint Repository

•   Nützlich für Randtechnologien

    •   Javascript

    •   DDL

    •   XSD/WSDL

    •   Spring

•   Dokumentation

•   Tooling

•   Dokumentationswerkzeuge

Der Bean Validation Standard JSR 303       28   Sandro Sonntag © Adorsys GmbH & Co KG
WEITERE INFORMATIONEN

•   JSR 303 - JCP.org

    •   http://jcp.org/en/jsr/detail?id=303

•   Agimatec

    •   http://www.agimatec.de/blog/2008/12/bean-validation-jsr-303-13-
        standard/

•   From a World of Constraints to Constrain the World

    •   http://www.jboss.org/file-access/default/members/default/freezone/
        presentations/JavaOne2008_JSR303BeanValidation.pdf
Der Bean Validation Standard JSR 303          29      Sandro Sonntag © Adorsys GmbH & Co KG
VIELEN DANK

 FRAGEN?
  Sandro Sonntag




        30

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Geprüfte Bohne - Der Bean Validation Standard

  • 1. © http://philowendeltreppe.wordpress.com/ GEPRÜFTE BOHNE Der Bean Validation Standard Sandro Sonntag 1 Sandro Sonntag © Adorsys GmbH & Co KG
  • 2. AGENDA © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 3. AGENDA • Bedarf und Notwendigkeit © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 4. AGENDA • Bedarf und Notwendigkeit • Existierende Lösungen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 5. AGENDA • Bedarf und Notwendigkeit • Existierende Lösungen • Der JSR 303 © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 6. AGENDA • Bedarf und Notwendigkeit • Existierende Lösungen • Der JSR 303 • JSR 303 Implementierungen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 7. AGENDA • Bedarf und Notwendigkeit • Constraints Deklarieren • Existierende Lösungen • Der JSR 303 • JSR 303 Implementierungen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 8. AGENDA • Bedarf und Notwendigkeit • Constraints Deklarieren • Existierende Lösungen • Gruppierungen • Der JSR 303 • JSR 303 Implementierungen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 9. AGENDA • Bedarf und Notwendigkeit • Constraints Deklarieren • Existierende Lösungen • Gruppierungen • Der JSR 303 • Messages • JSR 303 Implementierungen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 10. AGENDA • Bedarf und Notwendigkeit • Constraints Deklarieren • Existierende Lösungen • Gruppierungen • Der JSR 303 • Messages • JSR 303 Implementierungen • Eigene Constraints © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 11. AGENDA • Bedarf und Notwendigkeit • Constraints Deklarieren • Existierende Lösungen • Gruppierungen • Der JSR 303 • Messages • JSR 303 Implementierungen • Eigene Constraints • Metadaten lesen © delater / PIXELIO Der Bean Validation Standard JSR 303 2 Sandro Sonntag © Adorsys GmbH & Co KG
  • 12. WARUM VALIDIERUNG? © Ernst Rose / PIXELIO Der Bean Validation Standard JSR 303 3 Sandro Sonntag © Adorsys GmbH & Co KG
  • 13. WARUM VALIDIERUNG? • Validierung • Prüfung von Thesen • Sicherstellung der Datenqualität • Misstrauen des Nutzers • Prävention zur Vermeidung von Fehlern © Ernst Rose / PIXELIO Der Bean Validation Standard JSR 303 3 Sandro Sonntag © Adorsys GmbH & Co KG
  • 14. WARUM VALIDIERUNG? • Validierung • Prüfung von Thesen • Sicherstellung der Datenqualität • Misstrauen des Nutzers • Prävention zur Vermeidung von Fehlern • Sicherheits-Belange • Constraints © Ernst Rose / PIXELIO • Regeln der Prüfung • NotNull, Min, Max, Length Der Bean Validation Standard JSR 303 3 Sandro Sonntag © Adorsys GmbH & Co KG
  • 15. Webservice Browser Richclient Java Application Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 16. Webservice Browser Richclient Java Java Application Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 17. Webservice Browser Richclient Java Java Application Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 18. Webservice Browser Richclient Java Java Application Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 19. Webservice Browser Richclient Java Java Application Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 20. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 21. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO RDBM CONSTRAINTS IN TIERS 4
  • 22. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib RDBM CONSTRAINTS IN TIERS 4
  • 23. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib RDBM CONSTRAINTS IN TIERS 4
  • 24. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib WSDL RDBM CONSTRAINTS IN TIERS 4
  • 25. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib WSDL RDBM CONSTRAINTS IN TIERS 4
  • 26. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib WSDL RDBM DDL CONSTRAINTS IN TIERS 4
  • 27. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib WSDL RDBM DDL CONSTRAINTS IN TIERS 4
  • 28. Webservice Browser Richclient Java Java Application JavaScript Präsentation Business DAO Taglib WSDL RDBM DDL CONSTRAINTS IN TIERS •Gleiche Prüfungen über alle Schichten •(meist) ein Model 4
  • 29. AKTUELLE LÖSUNGEN Java Server Faces <h:inputText id="firstName" value="#{UserRegistration.user.firstName}"> <f:validateLength minimum="2" maximum="25" /> </h:inputText> public void validateEmail(FacesContext context, UIComponent toValidate, Object value) { String email = (String) value; if (email.indexOf('@') == -1) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage("Invalid Email"); context.addMessage(toValidate.getClientId(context), message); } } Der Bean Validation Standard JSR 303 5 Sandro Sonntag © Adorsys GmbH & Co KG
  • 30. POJO & DDL public void check(Address a) { if (a.getStreet() == null || a.getStreet().length() > 60) { throw new ValidationException("Street has not a valid value!"); } } Der Bean Validation Standard JSR 303 6 Sandro Sonntag © Adorsys GmbH & Co KG
  • 31. POJO & DDL public void check(Address a) { if (a.getStreet() == null || a.getStreet().length() > 60) { throw new ValidationException("Street has not a valid value!"); } } create table LOGIN ( id bigint not null auto_increment, login varchar(255) not null, name varchar(255) not null, password varchar(255) not null, primary key (id)); Der Bean Validation Standard JSR 303 6 Sandro Sonntag © Adorsys GmbH & Co KG
  • 32. NACHTEILE • Layerspezifische Validierungs Technologien • Code Duplizierung • Inkonsistenz • Verstreuung über den Code Der Bean Validation Standard JSR 303 7 Sandro Sonntag © Adorsys GmbH & Co KG
  • 33. BESSER WÄHRE DOCH © Ernst Rose / PIXELIO Der Bean Validation Standard JSR 303 8 Sandro Sonntag © Adorsys GmbH & Co KG
  • 34. BESSER WÄHRE DOCH • Einheitliche Deklaration der Constaints • In einer Sprache • Layer agnostisch © Ernst Rose / PIXELIO Der Bean Validation Standard JSR 303 8 Sandro Sonntag © Adorsys GmbH & Co KG
  • 35. BESSER WÄHRE DOCH • Einheitliche Deklaration der Constaints • In einer Sprache • Layer agnostisch • Validierung der Constraints • Durch wiederverwendbares API • In allen Schichten verwendbar © Ernst Rose / PIXELIO Der Bean Validation Standard JSR 303 8 Sandro Sonntag © Adorsys GmbH & Co KG
  • 36. DEKLARATION Der Bean Validation Standard JSR 303 9 Sandro Sonntag © Adorsys GmbH & Co KG
  • 37. DEKLARATION • Javadoc → Liest niemand Der Bean Validation Standard JSR 303 9 Sandro Sonntag © Adorsys GmbH & Co KG
  • 38. DEKLARATION • Javadoc → Liest niemand • XML Konfiguration → zu weit vom Code Der Bean Validation Standard JSR 303 9 Sandro Sonntag © Adorsys GmbH & Co KG
  • 39. DEKLARATION • Javadoc → Liest niemand • XML Konfiguration → zu weit vom Code • Taglib → Layer spezifisch Der Bean Validation Standard JSR 303 9 Sandro Sonntag © Adorsys GmbH & Co KG
  • 40. DEKLARATION • Javadoc → Liest niemand • XML Konfiguration → zu weit vom Code • Taglib → Layer spezifisch • @Annotation →Dicht am Code →Java! Der Bean Validation Standard JSR 303 9 Sandro Sonntag © Adorsys GmbH & Co KG
  • 41. FRAMEWORKS HEUTE Der Bean Validation Standard JSR 303 10 Sandro Sonntag © Adorsys GmbH & Co KG
  • 42. FRAMEWORKS HEUTE • Apache Commons Validator • JSF Validator • Xwork • Hibernate Validator • MyFaces Validation Der Bean Validation Standard JSR 303 10 Sandro Sonntag © Adorsys GmbH & Co KG
  • 43. JSR 303 Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 44. JSR 303 • Standardisieren von Constraints • Annotations • Implementierung eigener Constraints Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 45. JSR 303 • Standardisieren von Constraints • Annotations • Implementierung eigener Constraints • Validierungs API • Layerunabhängig • I18n • Extension Points Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 46. JSR 303 • Standardisieren von • Standardisierung der Constraints Metadata API • Annotations • Implementierung eigener Constraints • Validierungs API • Layerunabhängig • I18n • Extension Points Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 47. JSR 303 • Standardisieren von • Standardisierung der Constraints Metadata API • Annotations • Integration anderer • Implementierung eigener Frameworks Constraints • Validierungs API • Layerunabhängig • I18n • Extension Points Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 48. JSR 303 • Standardisieren von • Standardisierung der Constraints Metadata API • Annotations • Integration anderer • Implementierung eigener Frameworks Constraints • XML Konfiguration • Validierungs API • Layerunabhängig • I18n • Extension Points Der Bean Validation Standard JSR 303 11 Sandro Sonntag © Adorsys GmbH & Co KG
  • 49. JSR 303 Der Bean Validation Standard JSR 303 12 Sandro Sonntag © Adorsys GmbH & Co KG
  • 50. JSR 303 • Status • Proposed Final Draft (30 März, 2009) • RI in Glassfish V3 Der Bean Validation Standard JSR 303 12 Sandro Sonntag © Adorsys GmbH & Co KG
  • 51. JSR 303 • Status • Proposed Final Draft (30 März, 2009) • RI in Glassfish V3 • Spec Lead: Emmanuel Bernard Der Bean Validation Standard JSR 303 12 Sandro Sonntag © Adorsys GmbH & Co KG
  • 52. JSR 303 • Status • Proposed Final Draft (30 März, 2009) • RI in Glassfish V3 • Spec Lead: Emmanuel Bernard • Implementierungen • Hibernate Validator (RI) • Agimatec Validation Der Bean Validation Standard JSR 303 12 Sandro Sonntag © Adorsys GmbH & Co KG
  • 53. AGENDA • Constraints Deklarieren • Gruppierungen • Messages • Eigene Constraints • Metadaten lesen Der Bean Validation Standard JSR 303 13 Sandro Sonntag © Adorsys GmbH & Co KG
  • 54. CONSTRAINTS DEKLARIEREN • Basierend auf Java Annotations • Class, Getter, Setter @NotNull private String firstname; • Kreuzplausibilisierungen • Anpassbarkeit • Gruppen @Valid @NotNull(groups = First.class) private Author author; • Messages • Eigene Parameter Der Bean Validation Standard JSR 303 14 Sandro Sonntag © Adorsys GmbH & Co KG
  • 55. public class Person { @NotEmpty @NotNull private String firstname; @NotEmpty @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}") private String lastname; @NotNull @Valid private Address address; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } Der Bean Validation Standard JSR 303 } 15 Sandro Sonntag © Adorsys GmbH & Co KG
  • 56. ANNOTATIONS Der Bean Validation Standard JSR 303 16 Sandro Sonntag © Adorsys GmbH & Co KG
  • 57. •Logik •Fachlich •@NotNull •@Email •@NotEmpty •@EAN •@AssertTrue / False •@CreditCard •Wertebereich •Andere •@Min •@Valid •@Max •@Pattern •@Digits •@Size ANNOTATIONS Der Bean Validation Standard JSR 303 16 Sandro Sonntag © Adorsys GmbH & Co KG
  • 58. NÜTZLICHE DINGE • Muilti Constraints • @Patterns({@Pattern(regexp=“???“)}) • Vererbung • Superclass • Interface • Additiv • Collections, Maps, Arrays Der Bean Validation Standard JSR 303 17 Sandro Sonntag © Adorsys GmbH & Co KG
  • 59. VALIDATION API Validieren einer Bean Set<InvalidConstraint> errors = addressValidator.validate(address); Eines Properties validator.validateProperty(address, "city") Eines Wertes validator.validateValue(Address.class, "city", "Paris") Der Bean Validation Standard JSR 303 18 Sandro Sonntag © Adorsys GmbH & Co KG
  • 60. VALIDATION API • Validierungsergebnis ConstraintViolationImpl{ rootBean=org.adorsys.demo.validation.validategraph.Person@287811, propertyPath='lastname', message='The size of lastname must be between 3 and 30', leafBean=org.adorsys.demo.validation.validategraph.Person@287811, value=Sa} • Fehlgeschlagene Constraints • Ungültiger Wert • Fehlermeldung (i18n) • Bean Instanz Der Bean Validation Standard JSR 303 19 Sandro Sonntag © Adorsys GmbH & Co KG
  • 61. MESSAGES • Constraint Der Bean Validation Standard JSR 303 20 Sandro Sonntag © Adorsys GmbH & Co KG
  • 62. MESSAGES • Constraint • Definiert eine Default Message public @interface Max { String message() default "{validator.max}"; ... Der Bean Validation Standard JSR 303 20 Sandro Sonntag © Adorsys GmbH & Co KG
  • 63. MESSAGES • Constraint • Definiert eine Default Message public @interface Max { String message() default "{validator.max}"; ... • Kann überschrieben werden @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}") private String lastname; Der Bean Validation Standard JSR 303 20 Sandro Sonntag © Adorsys GmbH & Co KG
  • 64. MESSAGES • Constraint • Definiert eine Default Message public @interface Max { String message() default "{validator.max}"; ... • Kann überschrieben werden @Size(min=3, max=30, message="The size of lastname must be between {min} and {max}") private String lastname; • Kann programmatisch erstellt werden constraintValidatorContext.disableDefaultError(); constraintValidatorContext.addError("A programmatic error"); Der Bean Validation Standard JSR 303 20 Sandro Sonntag © Adorsys GmbH & Co KG
  • 65. MESSAGES Der Bean Validation Standard JSR 303 21 Sandro Sonntag © Adorsys GmbH & Co KG
  • 66. MESSAGES • Parameter Ersetzung • Constraint Parameter nutzbar • Value must be between {min} and {max} Der Bean Validation Standard JSR 303 21 Sandro Sonntag © Adorsys GmbH & Co KG
  • 67. MESSAGES • Parameter Ersetzung • Constraint Parameter nutzbar • Value must be between {min} and {max} • Externalizierbar • I18n Resource Bundle • ValidationMessages.properties Der Bean Validation Standard JSR 303 21 Sandro Sonntag © Adorsys GmbH & Co KG
  • 68. MESSAGES • Parameter Ersetzung • Constraint Parameter nutzbar • Value must be between {min} and {max} • Externalizierbar • I18n Resource Bundle • ValidationMessages.properties • MessageInterpolator austauschbar Der Bean Validation Standard JSR 303 21 Sandro Sonntag © Adorsys GmbH & Co KG
  • 69. GRUPPIERUNG VON CONSTRAINTS © staumichel / PIXELIO Der Bean Validation Standard JSR 303 22 Sandro Sonntag © Adorsys GmbH & Co KG
  • 70. GRUPPIERUNG VON CONSTRAINTS • Validierung eines Subsets von Constraints • Aktivierung von mehreren Gruppen möglich • Portionsweise Validierung in Prozessen/Wizards © staumichel / PIXELIO Der Bean Validation Standard JSR 303 22 Sandro Sonntag © Adorsys GmbH & Co KG
  • 71. GRUPPIERUNG VON CONSTRAINTS • Validierung eines Subsets von Constraints • Aktivierung von mehreren Gruppen möglich • Portionsweise Validierung in Prozessen/Wizards • Implementierung • Group = Interface • Vererbung von Gruppen durch „extends“ • Standard Gruppe = Default © staumichel / PIXELIO Der Bean Validation Standard JSR 303 22 Sandro Sonntag © Adorsys GmbH & Co KG
  • 72. GRUPPIERUNG VON CONSTRAINTS • Validierung eines Subsets von Constraints • Aktivierung von mehreren Gruppen möglich • Portionsweise Validierung in Prozessen/Wizards • Implementierung • Group = Interface • Vererbung von Gruppen durch „extends“ • Standard Gruppe = Default © staumichel / PIXELIO • GroupSequences zur Priorisierung möglich Der Bean Validation Standard JSR 303 22 Sandro Sonntag © Adorsys GmbH & Co KG
  • 73. @ValidAddress(groups=Address.AddressCheck.class) @GroupSequence({Address.Basic.class, Address.AddressCheck.class}) public class Address { /** * check the Address only if the default group is valid */ public interface AddressCheck {} public interface Basic {} @NotEmpty(groups=Basic.class) @NotNull(groups=Basic.class) private String address; @NotEmpty(groups=Basic.class) @NotNull(groups=Basic.class) private String zip; @NotEmpty(groups=Basic.class) @NotNull(groups=Basic.class) private String city; public String getAddress() { return address; } ... } Der Bean Validation Standard JSR 303 23 Sandro Sonntag © Adorsys GmbH & Co KG
  • 74. CUSTOM CONSTAINTS Der Bean Validation Standard JSR 303 24 Sandro Sonntag © Adorsys GmbH & Co KG
  • 75. CUSTOM CONSTAINTS @Constraint(validatedBy = NumericValidator.class) @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RUNTIME) • Eine Annotation public @interface Numeric { String message() default "not a numeric value"; Class<?>[] groups() default { }; } Der Bean Validation Standard JSR 303 24 Sandro Sonntag © Adorsys GmbH & Co KG
  • 76. CUSTOM CONSTAINTS @Constraint(validatedBy = NumericValidator.class) @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RUNTIME) • Eine Annotation public @interface Numeric { String message() default "not a numeric value"; Class<?>[] groups() default { }; } public class NumericValidator implements ConstraintValidator<Numeric, String>{ public void initialize(Numeric constraintAnnotation) { } • Ein Validator public boolean isValid(String numeric, ConstraintValidatorContext constraintValidatorContext) { try { Long.valueOf(numeric); } catch (NumberFormatException e) { return false; } return true; } } Der Bean Validation Standard JSR 303 24 Sandro Sonntag © Adorsys GmbH & Co KG
  • 77. CUSTOM CONSTAINTS @Numeric(message="A zip has to be numeric.") @Size(min=5, max=5, message="A zip must has a size of 5 digits.") @Constraint(validatedBy={GermanZipcodeValidator.class}) @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RUNTIME) public @interface GermanZip { Class<?>[] groups() default { }; } Der Bean Validation Standard JSR 303 25 Sandro Sonntag © Adorsys GmbH & Co KG
  • 78. COMPOSITE CONSTRAINTS • Baukasten • Codeduplizierung • Wiederverwendung von primitiven Constraints © RainerSturm / PIXELIO • Bessere Toolunterstützung durch Verwendung von Core Constaints Der Bean Validation Standard JSR 303 26 Sandro Sonntag © Adorsys GmbH & Co KG
  • 79. WEITERE FEATURES Der Bean Validation Standard JSR 303 27 Sandro Sonntag © Adorsys GmbH & Co KG
  • 80. WEITERE FEATURES • Parameter Override Der Bean Validation Standard JSR 303 27 Sandro Sonntag © Adorsys GmbH & Co KG
  • 81. WEITERE FEATURES • Parameter Override @Size @Constraint(validatedBy = FrenchZipcodeValidator.class) public @interface FrenchZipcode { String message() default "Wrong zipcode"; @OverridesParameter(constraint=Size.class, parameter="message") String sizeMessage() default "{beancheck.zipcode.size}"; } Der Bean Validation Standard JSR 303 27 Sandro Sonntag © Adorsys GmbH & Co KG
  • 82. WEITERE FEATURES • Parameter Override @Size @Constraint(validatedBy = FrenchZipcodeValidator.class) public @interface FrenchZipcode { String message() default "Wrong zipcode"; @OverridesParameter(constraint=Size.class, parameter="message") String sizeMessage() default "{beancheck.zipcode.size}"; } • Ein Constraint mehre Validatoren • @Constraint(validatedBy={SizeValidatorForCollection.class}) Der Bean Validation Standard JSR 303 27 Sandro Sonntag © Adorsys GmbH & Co KG
  • 83. WEITERE FEATURES • Parameter Override @Size @Constraint(validatedBy = FrenchZipcodeValidator.class) public @interface FrenchZipcode { String message() default "Wrong zipcode"; @OverridesParameter(constraint=Size.class, parameter="message") String sizeMessage() default "{beancheck.zipcode.size}"; } • Ein Constraint mehre Validatoren • @Constraint(validatedBy={SizeValidatorForCollection.class}) • Konfigurative Zuordnung • Trennung von Deklaration und Implementierung Der Bean Validation Standard JSR 303 27 Sandro Sonntag © Adorsys GmbH & Co KG
  • 84. METADATEN API • Zugiff auf das Constraint Repository • Nützlich für Randtechnologien • Javascript • DDL • XSD/WSDL • Spring • Dokumentation • Tooling • Dokumentationswerkzeuge Der Bean Validation Standard JSR 303 28 Sandro Sonntag © Adorsys GmbH & Co KG
  • 85. WEITERE INFORMATIONEN • JSR 303 - JCP.org • http://jcp.org/en/jsr/detail?id=303 • Agimatec • http://www.agimatec.de/blog/2008/12/bean-validation-jsr-303-13- standard/ • From a World of Constraints to Constrain the World • http://www.jboss.org/file-access/default/members/default/freezone/ presentations/JavaOne2008_JSR303BeanValidation.pdf Der Bean Validation Standard JSR 303 29 Sandro Sonntag © Adorsys GmbH & Co KG
  • 86. VIELEN DANK FRAGEN? Sandro Sonntag 30

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. Synchronit&amp;#xE4;t Constraints &amp;#x2194; Dokumentation\n Komplexit&amp;#xE4;t\n\n
  29. Java!\n
  30. Java!\n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. Beispiele!\n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. Demo PersonTest\n
  52. gleiches Beispiel verwenden\n
  53. gleiches Beispiel verwenden\n
  54. gleiches Beispiel verwenden\n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. @Constrain Klammer pr&amp;#xFC;fen\n
  67. @Constrain Klammer pr&amp;#xFC;fen\n
  68. @Constrain Klammer pr&amp;#xFC;fen\n
  69. @Constrain Klammer pr&amp;#xFC;fen\n
  70. BeanValidator beispiel\n
  71. \n
  72. \n