正在发送时,可选<integer>不存在

时间:2016-01-05 15:34:23

标签: spring spring-mvc spring-boot optional request-mapping

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

/Users/sso-config/target/ssoadmintools/setup --path /apps/openam/server --log /apps/openam/log --acceptLicense --debug /apps/openam/debug

现在当我发送 @RequestMapping(value = "/update", method = RequestMethod.POST) RestResponse updateId(@RequestParam(value = "cityId") Optional<Integer> cityId) { } 没有值时,cityId会返回false,这是错误的,因为我实际上在请求参数中包含了cityId.isPresent(),但我没有设置值。

我注意到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的请求?

1 个答案:

答案 0 :(得分:1)

  

如何区分homeCityIdhomeCityId的请求   空值和一个根本不包含homeCityId的请求?

作为一个案例,您必须处理@RequestMapping#params出现的情况,无论是否为空。然后你需要另一个缺席处理程序。

首先,您可以使用homeCityId@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() { 参数。

{{1}}

如果参数存在,Spring MVC将始终调用第一个(并且您可以访问其值。如果参数不存在,它将调用第二个。由于它不存在,所以&#39你无需担心。