繁体   English   中英

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

[英]How to check if an Integer variable of @RequestParam type in Spring is “empty”?

如果我有一个代码,其中:

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

是我的参数之一,我该怎么做才能防止用户为此参数指定“空”值?

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

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

但由于它是Integer类型,我不知道如何验证它,因为该变量不为null(因为它是在URL上通知的),尽管没有赋值。

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

HTTP://本地主机:8080 / MyProject的

HTTP://本地主机:8080 / myproject的量= 2222

但不是这个:

HTTP://本地主机:8080 / myproject的量=

如果量没有URL通过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";
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM