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 :
http://localhost:8080/pt?one=1
, the controller returns "Not Null" which is correct.http://localhost:8080/pt
, the controller returns "Null" which is correct.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.
- If empty string and null is considered as no input, you can refer to Check whether a string is not null and not empty to update your checking.
- If empty string and null has different meaning, then you don't need to do anything else.
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;
}