Spring MVC @Valid annotation for all controllers?

I've seen this beautiful mechanism:

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

Is it possible to allow @Valid annotation for all validated controllers? 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);

This seems to be a repetitive pattern, perhaps someone has already solved it? perhaps with aspects? I don't care if all my methods and controllers will have @Valid input, most DTOs they receive will be valid anyway (since no validation annotations are applied to them)

thank

0


source to share


1 answer


you cannot omit the @Valid annotation, as this is a way to tell spring that the dto to check is just the spring validation check. But having a BindingResult is not required for each of your methods. You can omit it completely. If you want to do something when the check fails, you can catch MethodArgumentNotValidException

which is called in this case from the exception handling method (for example, you can use an annotated class @ControllerAdvice

that will contain methods @ExceptionHandler

applied to all controllers - exception handling is a completely different topic, you can read more details on the relevant spring documentation on mvc exception handling )



+2


source







All Articles