The validators (@Validated @Valid) do not work with Spring and TomEE

后端 未结 1 1456
轻奢々
轻奢々 2021-01-27 08:13

Validators do not work with Spring and TomEE without Maven or Grade.

I created an elementary project. When I enter incorrect data, the validator simply does nothing (no

相关标签:
1条回答
  • 2021-01-27 08:32

    @PathVariable is not meant to be validated in order to send back a readable message to the user. As principle a pathVariable should never be invalid.

    If a pathVariable is invalid the reason can be a bug generated a bad url (an href in jsp for example). No @Valid is needed and no message is needed, just fix the code;

    "the user" is manipulating the url. Again, no @Valid is needed, no meaningful message to the user should be given.

    In both cases just leave an exception bubble up until it is catched by the usual Spring ExceptionHandlers in order to generate a nice error page or a meaningful json response indicating the error. In order to get this result you can do some validation using custom editors

    Still You want to validate PathVariable you can use org.springframework.validation.annotation.Validated to valid RequestParam or PathVariable

    Init ValidationConfig

    @Configuration
    public class ValidationConfig {
        @Bean
        public MethodValidationPostProcessor methodValidationPostProcessor() {
            MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
            return processor;
        }
    }
    

    Add @Validated to your controller handler class, Like :

    @RestController
    @Validated
    public class RestSpring {
    ....
    }
    

    Add validators to your handler method:

    @RequestMapping(value = "/crea/{cogome}/{nome}/{eta}/{altezza}", produces = "application/json")
      public  PersonaDTO creaPersona(
                    @PathVariable("cogome") @Pattern(regexp = "[A-Z]+[a-z][a-z]+") @Valid String strCognome,
                    @PathVariable("nome") @Valid @Pattern(regexp = "[A-Z]+[a-z][a-z]+") String strNome,
                    @PathVariable("eta") int intEta,
                    @PathVariable("altezza") int intAletezza) 
                    {
    
                    PersonaDTO persona=new PersonaDTO(strCognome,strNome,intEta,intAletezza);
    
                    return persona;
            }
    
    0 讨论(0)
提交回复
热议问题