Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring validate related request parameters

@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?

like image 375
Combo Avatar asked Apr 28 '26 00:04

Combo


1 Answers

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 
}
like image 187
kakabali Avatar answered Apr 30 '26 05:04

kakabali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!