简体   繁体   中英

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

If I have a code in which:

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

is one of my parameters, what can I do to prevent the user from assigning an "empty" value to this parameter?

For example: let's suppose they requested, on Postman, the URL http://localhost:8080/myproject?amount= exactly like this, without assigning a value to this parameter. How can I validate it in my code and prevent them from assigning an empty value to an Integer object? I mean, required really has to be defined as false - since it is not necessary for this parameter to be informed - but, if it is informed, it can't receive an empty value. If this parameter was an object of String type, I know I could just write a simple

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

but since it is of Integer type I don't know how to validate it, because the variable is not null (since it was informed on the URL), although no value will have been assigned.

In short: I want these to be allowed on URL call:

http://localhost:8080/myproject

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

But not this:

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

If amount is not passed in url http://localhost:8080/myproject?amount= , the by default amount value will be null, as Integer can contain null value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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