【问题标题】:@RequestParam and @PathVariable on the same variable in Spring Boot@RequestParam 和 @PathVariable 在 Spring Boot 中的同一变量上
【发布时间】:2018-07-10 13:13:46
【问题描述】:

在我的 Spring boot 微服务中,我需要有一个映射下一个 url 的专用端点

  • /delivery-options/myLabel
  • /delivery-options?label=myLabel

为了处理这两种情况,我尝试同时使用 @RequestParam@PathVariable 作为控制器的方法参数,但这两种情况都不起作用

@RequestMapping({"/delivery-options", "/delivery-options/{label}"})
public ResponseEntity<?> getDeliveryOptions(@RequestParam(value = "label", required = false) @PathVariable(value = "label", required = false) String label ) {

}

是否可以将两者都映射到一个变量?

【问题讨论】:

  • 将这些值映射到 2 个不同的变量,然后将这些值分配给另一个变量。
  • 我想了想,如果可以使用更高级的方式来做,那就很有趣了。
  • 使用@MatrixVariable

标签: spring-boot request-mapping


【解决方案1】:

我相信我们只能通过分配给两个不同的变量并将两者都设为 false 来做到这一点。

我知道这不是您正在寻找的解决方案,而且我相信另一种方法是声明两种不同的方法并将每个请求映射到其中一个,即使这不会产生重复的代码,因为您正在处理请求和映射根据输入服务层

@RequestMapping(value= {"/hello/{hi}","/hellodiff"}, method=RequestMethod.GET)
public void hello(@PathVariable(value="hi", required=false) String hi, 
@RequestParam(value="key", required=false) String key) {
    System.out.println("Output: "+ hi +" "+ key);

}

输出:

localhost:8080/hello/hey
Output: hey null

localhost:8080/hellodiff?key="cool"
Output: null "cool"

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 2023-03-11
    • 2021-06-04
    • 2014-08-16
    • 1970-01-01
    • 2012-11-22
    • 2021-04-12
    相关资源
    最近更新 更多