【问题标题】:Spring Mvc and MediaType for consumes in @RequestMapping for a get rest requestSpring Mvc 和 MediaType 在 @RequestMapping 中用于获取休息请求
【发布时间】:2015-11-18 06:44:43
【问题描述】:

我正在使用 Spring Boot 实现一个 REST 应用程序。 我想为@RequestMapping 注释指定consumes 参数。 其余的调用应该是这样的:

http: // mysite.com/resource/123

在控制器中我按如下方式处理:

    @RequestMapping(value = "/resource/{id}", method = RequestMethod.GET, 
consumes = XXX, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Scenario getResource(@PathVariable("id") final long id) {
        //...
    }

默认值,即 all,是显而易见的而不是具体的。那么,对于consumes,哪个应该是正确的MediaType

【问题讨论】:

    标签: java rest spring-mvc spring-boot


    【解决方案1】:

    根据documentationconsumes 必须匹配Content-Type 标头的值,因此您需要为映射发送的值取决于客户端在标头中设置的内容。

    【讨论】:

    • id 的例子呢?哪个是正确的 MediaType?
    • 你想达到什么目的?你问从 REST 的角度来看什么是正确的方法?
    • 是的,完全正确。有什么想法吗?
    【解决方案2】:

    只需一个路径变量,您就不需要任何内容​​类型。如果您将其留空,Spring 会将所有 /resource/{id} 请求映射到此处理程序,而不管内容类型标头如何。如果要指定内容类型,请选择默认类型,例如 text/plain。但请注意,您必须将请求更改为具有相同的内容类型标头。

    【讨论】:

      【解决方案3】:

      要使用来自 url 路径或 url 查询参数的数据,您无需显式指定任何媒体格式。它使用默认格式。

      @RequestMapping(value={"/resource/{id}"}, method={RequestMethod.GET})
      public String getResource1(@PathVariable("id") Long id){
          // other code here
          return "";
      }
      
      @RequestMapping(value={"/resource/{id}"}, method={RequestMethod.POST})
      public String getResource2(@PathVariable("id") Long id, @ModelAttribute Person person){
          // other code here
          return "";
      }
      

      【讨论】:

        【解决方案4】:

        这取决于您的要求。例如,如果你只想允许消费JSON,那么:

        @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, ...)
        

        如果你想消费多种媒体类型,那么你可以在一个数组中指定它们:

        @RequestMapping(consumes = {
                MediaType.APPLICATION_JSON_VALUE,
                MediaType.APPLICATION_XML_VALUE,
        }, ...)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-07
          • 2015-06-22
          • 2019-03-10
          • 2015-10-21
          • 1970-01-01
          • 2014-10-23
          • 1970-01-01
          相关资源
          最近更新 更多