Question about posts that write in annotations.

When an empty string is initialized to a variable, as in my case, should I get the output of the message in the console? Where should I see the output of this message?

@NotBlank (message = "First name can't be an empty field") @NotNull(message = "First name can't be an empty field") private static String name; public static void main(String[] args) { init(""); } public static void init(String value){ name = value; } 

    1 answer 1

    This annotation is part of the Java Bean Validation specification. In order to see these messages, you need to pass an invalid object through the validator. In the case of a container (web server), this validator can be invoked transparently. Here is an example of a function that validates a passed object and throws an exception if it is not valid.

     public static <T extends Object> void validate( T object ) throws RuntimeException{ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> valRes = validator.validate( object ); if( ! valRes.isEmpty() ){ StringBuilder sb = new StringBuilder("Validation failed for: "); sb.append(object); for( ConstraintViolation<T> fail : valRes) { sb.append("\n ").append( fail.getPropertyPath() ).append(" ").append( fail.getMessage() ); } throw new RuntimeException( sb.toString() ); } } 

    As a class for type T you can use any class whose fields are labeled, for example, with the annotation @NotNull .

    PS In general, these annotations should not be installed on static fields.

    • Tell me what happens in the case of a web service and validation? When writing a web service, I understand that code you wrote above is not necessary, since the container calls this validator on its own? I can not understand the process of validation in the presence of a web service and requests for this web service? Where is it started and who is responsible for it, how are the messages displayed in annotations when validation is not correct? - Maks.Burkov
    • @ maks.burkov something like this. When building a web service, the container examines the method signatures for the presence of arguments that have corresponding annotations. Accordingly, before calling the method itself, the arguments are first given to the validator, and if it finds inconsistencies, then instead of calling the final function, an error handler is called. In general, this topic is quite extensive, so first study the documentation, and then ask additional questions. - Temka, too,