【问题标题】:REST API endpoint selection in Spring BootSpring Boot 中的 REST API 端点选择
【发布时间】:2017-06-22 11:38:20
【问题描述】:

给定一个这样的控制器:

   @RestController
   @RequestMapping("/cars") {
   public class CarController{

   @RequestMapping(method = RequestMethod.GET)
   public ResponseEntity<List<Cars>> getCars() { //logic }

   @RequestMapping(method = RequestMethod.GET")
   public ResponseEntity<List<Cars>> searchCar(@RequestParam("name") String name, @RequestParam("value") String value) { //logic}
  }

如果 url 是这样的 localhost/cars 我想访问 getCars() 方法。

但如果网址是: localhost/cars?name=something&value=100 或

localhost/cars?name=something 或

localhost/cars?value=100

我想访问第二种方法。

这样可以吗?

【问题讨论】:

  • 我不认为这是可能的,我建议只使用“/car”端点作为第二种方法。

标签: spring rest endpoint


【解决方案1】:

您仍然要求相同的资源列表,汽车,唯一的问题是您要添加过滤器或搜索/查询条件。

开发一个查询过滤器/标准来支持以下内容将是有益的:

/cars?q=make+eq+acura (meaning make=acura)
/cars?q=price+lt+25000  (meaning price <25000)

等等。

【讨论】:

    【解决方案2】:

    不,这是不可能的。因为当请求到达容器时,它将首先扫描所有 URL 并检查 URL 的唯一性。如果存在重复的 URL,则容器将抛出异常。

    在您的情况下,您使用的是类级别的 URL 映射,但您没有使用方法级别的 URL 映射。

    要访问您的 getCars() 方法,您需要使用如下 URL

    @RequestMapping(value = "/", method = RequestMethod.GET)
    

    要访问您的第二种方法,您需要使用另一个映射 URL

    @RequestMapping(values="/test", method = RequestMethod.GET")
    

    你无法访问

    localhost/cars?name=something&value=100 or
    
    localhost/cars?name=something or
    
    localhost/cars?value=100
    

    当您使用 2 个参数时,例如 @RequestParam("name") String name, @RequestParam("value") String value 您需要在您的网址中传递两个参数,如下所示

    localhost/cars/test?name=something&value=100
    

    如果您不想传递两个参数中的任何一个,那么只需将其作为null 传递并在您的方法中检查它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-05
      • 2023-03-18
      • 2017-03-14
      • 2020-10-29
      • 1970-01-01
      • 2017-06-28
      • 2020-10-27
      • 1970-01-01
      相关资源
      最近更新 更多