【问题标题】:How to check if an Integer variable of @RequestParam type in Spring is "empty"?如何检查Spring中@RequestParam类型的整数变量是否为“空”?
【发布时间】:2019-04-24 19:28:24
【问题描述】:

如果我有一个代码:

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

是我的参数之一,我该怎么做才能防止用户给这个参数分配一个“空”值?

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

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

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

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

http://localhost:8080/myproject

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

但不是这个:

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

【问题讨论】:

  • Spring MVC 应该无法转换查询参数并抛出异常,并且可能会向客户端返回 400。您是否尝试过点击那个 bad 网址?发生了什么?
  • http://localhost:8080/myproject?amount 将设置 amount = null 我认为。或者它在我的项目中。
  • @Savior 它什么都不做。 Spring 没有显示错误。
  • 那么amount的值是多少?
  • 您是否尝试在该控制器方法中放置一个断点并查看调试器中发生了什么?这是识别它如何实际解析这些不同输入的最佳方式。

标签: java spring spring-mvc object


【解决方案1】:

如果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";
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多