springstringspring-bootspring-restcontrollerhttp-request-parameters

Spring Boot non-required @RequestParam with String Data Type


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?


Solution

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

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