3

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?

3 Answers 3

2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

ok, that's what I was missing. Thank you
1

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.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.