可选<Integer> 发送时不存在

Optional<Integer> not present while it's being sent

我有一个像这样的控制器方法

  @RequestMapping(value = "/update", method = RequestMethod.POST)
  RestResponse updateId(@RequestParam(value = "cityId") Optional<Integer> cityId) {
  }

现在当我发送没有值的 cityId 时,cityId.isPresent() returns 是错误的,因为我实际上在我的请求参数中包含了 cityId 但我只是没有'不设置值。

我注意到 Optional<String> 上没有发生这种行为,它实际上告诉我参数存在,即使它没有值。

那么我应该如何处理 Optional<Integer> 之类的参数呢?我只需要确定参数是否已发送,即使它没有值(因为它是可选的,如果发送时没有值我必须更新数据库)

编辑: 看来我上面写的比较乱,我再描述一下问题

@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");
    }
}

我发出一个包含空值 homeCityId 的请求,我得到 homeCityId is Not Present。如何区分 homeCityId 为空值的请求和根本不包含 homeCityId 的请求?

How can I distinguish between a request that have homeCityId with an empty value and a request that didn't include homeCityId at all?

无论是否为空,您都必须将 homeCityId 存在的情况作为一个案例来处理。然后你需要另一个处理程序来处理缺席。

首先,您可以使用@RequestMapping#paramshomeCityId设置为调用处理程序的必要参数映射。

@RequestMapping(value = "/temp", params = { "homeCityId" }, method = RequestMethod.POST)
public String present(@RequestParam(value = "homeCityId") Integer homeCityId) {

然后检查homeCityId是否为null

其次,有第二个处理程序不需要 homeCityId 参数。

@RequestMapping(value = "/temp", method = RequestMethod.POST)
public String notPresent() {

Spring 如果参数存在,MVC 将始终调用第一个(并且您可以访问它的值。如果参数不存在,它将调用第二个。因为它不存在,所以没有价值替你操心。