如何检查 Spring 中@RequestParam类型的整数变量是否"empty"?



如果我有一个代码:

@RequestParam(value = "amount", required = false) Integer amount

是我的参数之一,我该怎么做才能防止用户为此参数分配"空"值?

例如:假设他们在 Postman 上请求 URLhttp://localhost:8080/myproject?amount=完全像这样,而不为此参数赋值。如何在代码中验证它并防止它们为 Integer 对象分配空值? 我的意思是,required确实必须定义为false- 因为没有必要通知此参数 - 但是,如果它被通知,它就无法接收空值。 如果这个参数是字符串类型的对象,我知道我可以写一个简单的

if (amount.isEmpty()) {
...
}

但由于它是整数类型,我不知道如何验证它,因为变量不是空的(因为它是在 URL 上通知的),尽管不会分配任何值。

简而言之:我希望在URL调用中允许这些:

http://localhost:8080/myproject

http://localhost:8080/myproject?amount=2222

但不是这个:

http://localhost:8080/myproject?amount=

如果在 urlhttp://localhost:8080/myproject?amount=中传递 amount,则默认amount值将为 null,因为 Integer 可以包含 null 值

@RequestMapping("/create3")
public String create3(@RequestParam Integer amount){
if(amount == null){
//return bad request
}
System.out.println("amount: "+amount);
return "Done";
}

最新更新