java - 如何Spring @requestparam验证字符串在字符串列表中

标签 java spring validation spring-mvc

我正在尝试用 @Valid 注释替换下面 Controller 中的硬编码验证

@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的列表不是静态的 还有其他 Spring 方法吗?

最佳答案

当您根据自定义列表进行验证时,没有开箱即用的方法来执行此操作。但是,要验证类型,您可以将 FruitType 定义为 enum 并使用 @RequestParam 对其进行注释,例如:

enum FruitType{
    Apple,
    Banana,
    Orange;
}

public List<String> fruits(
@RequestParam(value = "fruitType") FruitTypefruitType) {
//Implementation

关于java - 如何Spring @requestparam验证字符串在字符串列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44734506/

相关文章:

java - 表单验证失败时填充模型的最佳方法?

python - 过滤数据框中具有相同值的列 - Python

python - Tkinter validatecommand 命令会破坏参数类型吗?

java - 如何在Android项目中使用docxj4

java - Java 中的 XML RPC 问题——无法创建 XML 解析 : org. xml.sax.SaxNotRecognizedException

java - 如何在 powershell 中处理 $PSScriptRoot 路径中的空格

java - 书 : Modern day equivalent of the Wrox Spring book

java - 如何通过 application.properties 禁用 spring-security?

java - UnsatisfiedDependencyException : Error creating bean with name 'entityManagerFactory'

java - 在指定路径下发布Jax-WS Webservice