【问题标题】:Default mime type per Controller for Spring MVC's content negotiationSpring MVC 内容协商的每个控制器的默认 mime 类型
【发布时间】:2013-06-26 20:25:15
【问题描述】:

有没有办法为使用 Spring 的内容协商功能的 Spring MVC 控制器配置默认 mime 类型,即

ControllerA - 我希望默认的 mime 类型是 JSON,所以 http://mycompany.com/myresourceA 将返回 JSON,如果我想要 XML,我必须添加扩展名 http://mycompany.com/myresourceA.xml

ControllerB - 我希望默认的 mimetype 是 XML,所以 http://mycompany.com/myresourceB 将返回 XML,如果我想要 JSON,我必须添加扩展名 http://mycompany.com/myresourceB.json

在我的contentNegotiationManagerBean 中,我将默认 mime 类型设置为 XML,但这是一个全局配置

<property name="defaultContentType" value="application/xml" />

【问题讨论】:

    标签: spring-mvc serialization content-negotiation


    【解决方案1】:

    无法为整个控制器设置 mime 类型。您可以使用 ResponseEntity 作为您的操作方法的返回类型为您的操作设置它,然后为该操作设置响应类型。

    查看更多文档:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-httpentity

    使用 ResposneEntity 响应 JSON 的示例:

    @RequestMapping(method=RequestMethod.GET, value="/fooBar")
        public ResponseEntity<String> fooBar2() {
          String json = "jsonResponse";
          HttpHeaders responseHeaders = new HttpHeaders();
          responseHeaders.setContentType(MediaType.APPLICATION_JSON);
          return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 2011-04-06
      • 2014-06-15
      • 1970-01-01
      • 2016-02-28
      相关资源
      最近更新 更多