@RequestMapping(value = "/test")
@ResponseBody
public Object test(@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude) {
}
In this case if latitude is not null than longitude must be not null.
How to validate related request parameters? Is there out-of-the-box solution, or to validate manually?
If you are using recent version of the spring then there is a annotation @Validated.
With this annotation we can validate both @RequestParam and @PathVariable
The most important thing to notice is that @Valid which is used to validate the RequestBody throws the exception MethodArgumentNotValidException
While the @Validated throws ConstraintViolationException
Because both of the exceptions are of different types you have to handle them differently using @ExceptionHandler, something like below:-
@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleConstraintViolationException(ConstraintViolationException e) {
// your code here to handle the exceptions accordingly
}
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
// your code here to handle the exceptions accordingly
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With