如果我有一个代码:
@RequestParam(value = "amount", required = false) Integer amount
是我的参数之一,我该怎么做才能防止用户为该参数分配“空”值?
例如:假设他们在 Postman 上请求 URL http://localhost:8080/myproject?amount= 与此完全相同,无需为此参数分配值。如何在代码中验证它并防止他们将空值分配给 Integer 对象? 我的意思是,required确实必须被定义为false - 因为没有必要通知这个参数 - 但是,如果被通知,它就无法接收一个空值。 如果这个参数是一个String类型的对象,我知道我可以写一个简单的
if (amount.isEmpty()) {
...
}
但由于它是 Integer 类型,我不知道如何验证它,因为该变量不为 null(因为它是在 URL 上通知的),尽管不会分配任何值。
简而言之:我希望在 URL 调用中允许这些:
http://localhost:8080/myproject
http://localhost:8080/myproject?amount=2222
但不是这个:
最佳答案
如果 URL 中未传递 amount http://localhost:8080/myproject?amount=
,默认情况下 amount
值为 null,因为 Integer 可以包含空值
@RequestMapping("/create3")
public String create3(@RequestParam Integer amount){
if(amount == null){
//return bad request
}
System.out.println("amount: "+amount);
return "Done";
}
关于java - 如何检查Spring中@RequestParam类型的Integer变量是否为 "empty"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55837237/