Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play framework @Required

I am new to Java and play. going through the sample applications. can you help me understand what it is going on in this file. https://github.com/playframework/Play20/blob/master/samples/java/forms/app/models/User.java

I don't understand why we declare this interface "public interface All {}" and how it is being used in this validation. "@Required(groups = {All.class, Step1.class})"

like image 291
vinos Avatar asked Mar 06 '13 01:03

vinos


1 Answers

@Required is a custom JSR-303 annotation, created within the Play framework. JSR-303 is a specification for validation of Javabeans, which allows for ensuring that a given Java bean's values fall within a set of constraints. Examples of some standard validation annotations:

  • @Max - The annotated element must be a number whose value must be lower or equal to the specified maximum.
  • @Min - The annotated element must be a number whose value must be higher or equal to the specified minimum.
  • @NotNull - The annotated element must not be null.

Each JSR-303 annotation is allowed to define groups, where each group is really just a class. These groups can be used to execute a subset of validations for a given bean. In your particular example, the implementors have defined two interfaces to represent these groups - All and Step1. Then they add the groups to the validation annotations, in order to indicate that those validations belong to the group. So for the below class:

public class MyBean {
    @Required(groups = {All.class, Step1.class})
    @MinLength(value = 4, groups = {All.class})
    public String username;
}

MyBean bean = new MyBean();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

The following will execute the @Required and @MinLength validation for the username field:

validator.validate(bean, All.class);

Whereas the following will execute just the @Required validation (for the username field):

validator.validate(bean, Step1.class);
like image 127
Perception Avatar answered Oct 20 '22 01:10

Perception