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