【问题标题】:Avoid ambigous GetMapping in Spring boot Rest避免 Spring Boot Rest 中的歧义 GetMapping
【发布时间】:2018-12-20 14:27:22
【问题描述】:

我有两个 GET 请求

@GetMapping
public List<Limit> getAllLimits(@RequestParam() Map<String, String> limitFilters) throws ApiException {
    if(CollectionUtils.isEmpty(limitFilters)) {
        return limitService.getAllLimits();
    }
    else {
        return limitService.getLimitBySearchFilters(limitFilters);
    }
}

@GetMapping(params = { "id", "asOfDate" })
public Limit getLimitByid(@RequestParam Long id, @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "asOfDate", required = false) LocalDate asOfDate) throws EntityNotFoundException, ApiException {
    return limitService.getLimitById(id, asOfDate);
}

@GetMapping({"/{pid}"})
public Limit getLimitByPid(@PathVariable Long pid) throws EntityNotFoundException, ApiException {
    return limitService.getLimitByPid(pid);
}

但是,请注意asOfDate 是可选的 所以,http://localhost:8080/limit?id=1 转到 getAllLimits(@RequestParam() Map&lt;String, String&gt; limitFilters) 而我希望它路由到 getLimitByid() 方法

我怎样才能做到这一点?任何帮助将不胜感激

【问题讨论】:

    标签: java spring-mvc spring-boot microservices restful-url


    【解决方案1】:

    我终于找到了办法:

    @GetMapping(params = { "id" })
    public Limit getLimitByid(@RequestParam Long id, @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(name = "asOfDate") Optional<LocalDate> opAsOfDate) throws EntityNotFoundException, ApiException {
        LocalDate asOfDate = opAsOfDate.orElse(LocalDate.now());
        return limitService.getLimitById(id, asOfDate);
    }
    
    @GetMapping({"/{pid}"})
    public Limit getLimitByPid(@PathVariable Long pid) throws EntityNotFoundException, ApiException {
        return limitService.getLimitByPid(pid);
    }
    

    【讨论】:

      【解决方案2】:

      正如javadocs 中所说,@RequestParam Map&lt;String, String&gt; limitFilters 告诉 spring 将任何请求参数映射到这个 Map

      如果方法参数是Map&lt;String, String&gt;MultiValueMap&lt;String, String&gt; 且未指定参数名称, 然后使用所有请求参数名称填充 map 参数 和价值观。

      所以想象一下你的过滤器中有id 参数。它会弄乱你的控制器。所以最简单的方法是改变路径

      【讨论】:

      • 对此的任何参考
      • 编辑了我的答案。其实http://localhost:8080/limit?id=1&amp;asOfDate=2018-07-12的请求可以被getAllLimits处理,不知道为什么会如你所愿
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 2016-02-09
      • 1970-01-01
      • 2019-04-30
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多