Home > Enterprise >  Is there any way to determine if a request parameter value is null, or if the request parameter is n
Is there any way to determine if a request parameter value is null, or if the request parameter is n

Time:10-20

how to distinguish between two scenarios

1. The parameter value is null in the request
2. The parameter is not passed in the request 

the request param just looks like this:

var=null or {"var":null}

In both scenarios I described inside the question, the variable values of the request parameters obtained are null.

But we have business logic that needs to distinguish between these two scenarios.

If the user actively provides the null value, we need to do other processing

How to achieve this goal? Is there a good way to do this in a real production environment?

Many thanks

CodePudding user response:

If you're talking about query or form parameters, then these cannot take value null. They are sent as strings; any conversion (e.g. to int) is done by the framework or your own application. So if a query parameter is sent in as ?var=null, then your applications gets 'null' - a string of length 4 containing the word null. So, if your application receives a null, then the query / form parameter was not sent.

It's a different story when you're talking about properties in JSON. If the type is simply String, Integer, etc., then you cannot see the difference between not-present and present as null. You can try using Optional<String> etc., but I haven't tried that myself. For Jackson you can find more information at https://www.baeldung.com/jackson-optional.

CodePudding user response:

to make sure request parameter is not null and is always present you can use

@RequestParam(required = true )

This will make sure parameter is always passed

  • Related