4

Iv'e seen this nice mechanism:

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

Is it possible to make the @Valid annotation avaialble for all the Controllers with validation? It seems very redundant to do the following:

@RequestMapping(value = "/getPlayerAccounts", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public QueryResultsDTO<PlayerAccountResultDTO> getPlayerAccounts(@RequestBody **@Valid** FilteredQueryRequestDTO filteredQueryRequestDTO,
                                 **BindingResult result**) {

**this.validateDTO(result);**
return this.playerService.getPlayerAccounts(filteredQueryRequestDTO);
}

Reduandant code:

@Valid

BindingResult result

this.validateDTO(result);

These seems like a recurring pattern, probably someone already solved it? maybe with aspects? I dont care that all my methods and controllers will have the @Valid login, most of the DTOs they recieve will be valid anyway (since no validation annotations are applied to them)

Thanks

Urbanleg
  • 6,252
  • 16
  • 76
  • 139

1 Answers1

3

you cannot omit @Valid annotation, since this is the way to tell spring which dto to validate, that is just the way the spring validation works. But having a BindingResult result to each of your methods is not necessary. You may omit it completely. If you want to do something when validation fails, you can catch the MethodArgumentNotValidException that is thrown in that case from an exception handling method (e.g you can use a class with @ControllerAdvice annotations that will contain @ExceptionHandler methods applied to all controllers - exception handling is a whole different topic, you can read more details on related spring mvc exception handling documentation)

Marios
  • 1,947
  • 1
  • 15
  • 24
  • 3
    Don't know if things changed since '14 but I could ommit @Valid and enforce validation always. This is the way could make it: https://stackoverflow.com/questions/44722000/how-to-spring-get-rid-of-validate-for-automatic-controller-validation – Gerard Bosch Aug 05 '17 at 14:12