如何在字符串列表中播放@RequestParam validate String



我试图用@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使用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;
    }

但是,如果Fruittype的列表不是静态的还有其他弹簧方法吗?

当您针对自定义列表进行验证时,没有任何障碍的方法可以做到这一点。但是,要验证类型,您可以将FruitType定义为enum并用@RequestParam进行注释,例如:

enum FruitType{
    Apple,
    Banana,
    Orange;
}
public List<String> fruits(
@RequestParam(value = "fruitType") FruitTypefruitType) {
//Implementation

您可以使用枚举来验证值并投掷自定义错误,可以使用@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);
        }
    }

最新更新