我正在尝试使用@Valid注释替换下面控制器中的硬编码验证
@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;
}
我知道我可以使用@Pattern来检查这个使用正则表达式,
@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;
}
但是如果fruitType列表不是静态的 还有其他春天的方法吗?
答案 0 :(得分:0)
当您对自定义列表进行验证时,没有开箱即用的方法来执行此操作。但是,要验证类型,您可以将FruitType
定义为enum
并使用@RequestParam
进行注释,例如:
enum FruitType{
Apple,
Banana,
Orange;
}
public List<String> fruits(
@RequestParam(value = "fruitType") FruitTypefruitType) {
//Implementation
答案 1 :(得分:0)
您可以使用枚举来验证值并抛出可以使用@RestControllerAdvice的自定义错误。示例代码如下。
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;
}
//下面是控制器顾问的示例类..
@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);
}
}