I am trying to replace hardcoded validation in below controller with @Valid annotation
@GetMapping(value = "/fruits")
public List<String> fruits(
@RequestParam(value = "fruitType", defaultValue = "") String fruitType) {
final ImmutableList<String> fruitTypes =
ImmutableList.of("Citrus", "Seed Less", "Tropical");
if (!fruitTypes.contains(fruitType)) {
throw new RuntimeException("Invalid Fruit type");
}
final ImmutableList<String> fruits =
ImmutableList.of("Apple", "Banana", "Orange");
//filter fruits based on type, then return
return fruits;
}
I know I can use @Pattern to check this using regex,
@GetMapping(value = "/fruits")
public List<String> fruits(@RequestParam(value = "fruitType", defaultValue = "")
@Valid @javax.validation.constraints.Pattern(regexp="Citrus|Seed Less|Tropical")
String fruitType) {
// final ImmutableList<String> fruitTypes = ImmutableList.of("Citrus", "Seed Less", "Tropical");
// if (!fruitTypes.contains(fruitType)) {
// throw new RuntimeException("Invalid Fruit type");
// }
final ImmutableList<String> fruits = ImmutableList.of("Apple", "Banana", "Orange");
//filter fruits based on type, then return
return fruits;
}
But if the list of fruitType is not static Is there any other spring way to do it ?
As you are validating against custom list, there is no out of the box way to do this. However, to validate the types, you can define FruitType
as enum
and annotate it with @RequestParam
, eg:
enum FruitType{
Apple,
Banana,
Orange;
}
public List<String> fruits(
@RequestParam(value = "fruitType") FruitTypefruitType) {
//Implementation
You can use enum to validate the value and to throw the custom error you can use @RestControllerAdvice. Sample code is below.
enum FruitType {
Apple, Banana, Orange;
}
@GetMapping(value = "/fruits")
public List<String> fruits(@RequestParam(value = "fruitType") FruitType fruitType) {
// You can put your business logic here.
return fruits;
}
//below is sample class for controller adviser..
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<MpsErrorResponse> exceptionToDoHandler(HttpServletResponse response,
MethodArgumentTypeMismatchException ex) throws IOException {
return new ResponseEntity<>(new MpsErrorResponse(HttpStatus.NOT_FOUND.value(), "Invalid Fruit type"),
HttpStatus.NOT_FOUND);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.