如何检查Spring中@RequestParam类型的Integer变量是否为“空”?

时间:2019-04-24 19:28:25

标签: java spring spring-mvc object

如果我有以下代码:

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

是我的参数之一,如何防止用户为该参数分配“空”值?

例如:假设他们在邮递员上要求的URL http://localhost:8080/myproject?amount= 与此完全相同,而没有为该参数分配值。如何在我的代码中验证它并防止它们将空值分配给Integer对象? 我的意思是 required 实际上必须定义为 false -因为没有必要通知此参数-但是,如果通知了该参数,它将无法接收一个空值。 如果这个参数是String类型的对象,我知道我可以写一个简单的

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

但是由于它是Integer类型的,所以我不知道如何验证它,因为该变量不是空值(因为它是通过URL通知的),尽管不会分配任何值。

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

http://localhost:8080/myproject

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

但不是这样:

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

1 个答案:

答案 0 :(得分:0)

如果未在网址http://localhost:8080/myproject?amount=中传递金额,则默认情况下amount的值为空,因为整数可以包含空值

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