Home > Mobile >  Spring Boot non-required @RequestParam with String Data Type
Spring Boot non-required @RequestParam with String Data Type

Time:08-08

Here is a example Controller :

@GetMapping("/pt")
public String getPt(@RequestParam(value = "one", required = false) String one) {
    if(one != null) {
        return  "Not Null";
    } else {
        return  "Null";
    }
}

So When I call the URL :

  1. http://localhost:8080/pt?one=1, the controller returns "Not Null" which is correct.

  2. http://localhost:8080/pt, the controller returns "Null" which is correct.

  3. http://localhost:8080/pt?one=, the controller returns "Not Null", Is this correct?

when the value for the param is not provided, it should be null, shouldn't it? Or Is there anything else with this?

This only happens with String Data Type, with other Data Types like Integer, Long, the third URL pattern returns Null as expected.

why is this happening? Is there anything else that should be done with String or checking the String for null is wrong?

CodePudding user response:

http://localhost:8080/pt?one= , -> String one = "";

one = "" considered value , But if you say : one = null , It means that the value null

CodePudding user response:

http://localhost:8080/pt?one=, the controller returns "Not Null", Is this correct?

Yes, one is mapped to empty string "" in this case.

This only happens with String Data Type, with other Data Types like Integer, Long, the third URL pattern returns Null as expected.

It is totally valid to map empty string for String. But for Integer and Long, there is no valid mapping, so null is returned.

Is there anything else that should be done with String or checking the String for null is wrong?

It depends on your use case.

CodePudding user response:

Use defaultValue property when the request param is not provided or is empty.

@GetMapping("/pt")
public String getPt(@RequestParam(value = "one", defaultValue = "-1") String one) {
   if(one == "-1") {
      return "Required element of request param";
   }
   return one;
}
  • Related