I have a controller method like so
@RequestMapping(value = "/update", method = RequestMethod.POST)
RestResponse updateId(@RequestParam(value = "cityId") Optional<Integer> cityId) {
}
Now when I send cityId
without a value, cityId.isPresent()
returns false, which is wrong because I actually included cityId
in my request parameters but I just didn't set a value.
I noticed this behavior doesn't happen on Optional<String>
, it actually tells me that the parameter is present even if it doesn't have a value.
So how should I handle parameters the likes of Optional<Integer>
? I just need to determine that the parameter was sent even if it had no value (because it's optional and if it was sent without a value I have to update the database)
edit: Looks like what I wrote above is confusing, I'll try to describe the issue again
@RequestMapping(value = "/temp", method = RequestMethod.POST)
void temporary(@RequestParam(value = "homeCityId") Optional<Integer> homeCityId) {
if(homeCityId.isPresent()) {
System.out.println("homeCityId is Present");
} else {
System.out.println("homeCityId is Not Present");
}
}
I make a request that includes homeCityId
with an empty value, I get homeCityId is Not Present
. How can I distinguish between a request that have homeCityId
with an empty value and a request that didn't include homeCityId
at all?
How can I distinguish between a request that have
homeCityId
with an empty value and a request that didn't includehomeCityId
at all?
You'll have to handle the case of homeCityId
being present, regardless of empty or not, as a single case. Then you'll need another handler for absence.
First, you can use @RequestMapping#params
to set homeCityId
as a necessary parameter mapping for the handler to be invoked.
@RequestMapping(value = "/temp", params = { "homeCityId" }, method = RequestMethod.POST)
public String present(@RequestParam(value = "homeCityId") Integer homeCityId) {
Then check if homeCityId
is null
or not.
Second, have a second handler that doesn't require the homeCityId
param.
@RequestMapping(value = "/temp", method = RequestMethod.POST)
public String notPresent() {
Spring MVC will always invoke the first if the parameter is present (and you'll have access to its value. It will invoke the second if the parameter is absent. Since it's absent, there's no value for you to worry about.