gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:42:09 24 4
gpt4 key购买 nike

我正在尝试用 @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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com