【问题标题】:spring rest web service how to solve ambiguous getspring rest web service如何解决get的歧义
【发布时间】:2018-03-09 03:35:04
【问题描述】:

我有一个 Spring Web 服务休息。

我有两个得到:

// VIEW PRODUCT DETAILS

        @RequestMapping(value="/products/{prodId}", method=RequestMethod.GET)
        public @ResponseBody Product productView(@PathVariable("prodId") int prodId) {
            logger.info("======= in productView (REST)");
            Product product = inventoryService.findProductById(prodId); 
            return product;
        }

         // VIEW PRODUCT DETAILS NAME

        @RequestMapping(value="/products/{prodName}", method=RequestMethod.GET)
        public @ResponseBody Product productNameView(@PathVariable("prodName") String prodName) {
            logger.info("======= in  productNameView (REST)");
            Product product = inventoryService.findProductByName(prodName); 
            return product;
        }

当我使用 get 时,我得到了一个模棱两可的信息

http://localhost:8080/rest/products/627790"

我怎样才能有两个不同的get?

【问题讨论】:

    标签: spring rest service get


    【解决方案1】:

    您可以使用用户查询参数方法:

        @RequestMapping(value="/products/{prodId}", 
           method=RequestMethod.GET, params = "type=prodId" )
    
        @RequestMapping(value="/products/{prodName}", 
         method=RequestMethod.GET, params = "type=prodName")
    

    使用以下网址拨打电话:

    http://localhost:8080/rest/products/123?type=prodId"

    http://localhost:8080/rest/products/456?type=prodName"

    告诉我它对你有帮助。

    【讨论】:

      【解决方案2】:

      那是因为当 url */products/627790 被命中时,627790 可以被视为 int 和 string。 rest 如何知道要调用哪个控制器?

      为避免在您的情况下产生歧义,您应该使用@RequestParam 而不是@PathVariable。客户端的 URL 将发生变化,但代码将更具可读性和可解析性。

      所以,

      @RequestMapping(value="/products", method=RequestMethod.GET)
      public @ResponseBody Product productView(@RequestParam("prodId") int prodId) {}
      
      
      @RequestMapping(value="/products", method=RequestMethod.GET)
      public @ResponseBody Product productNameView(@RequestParam("prodName") String prodName) {}
      

      您的网址将是:

      http://localhost:8080/rest/products/prodId=627790"

      http://localhost:8080/rest/products/prodName=myProduct"

      【讨论】:

        猜你喜欢
        • 2022-11-04
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 2017-03-19
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多