【问题标题】:Setting the response content-type without using HttpServletResponse在不使用 HttpServletResponse 的情况下设置响应内容类型
【发布时间】:2012-01-19 14:50:22
【问题描述】:

如何在我的 spring 控制器中的方法中获取 HttpServletResponse object以便我的应用程序与 Http API 保持松散耦合?

谢谢...

编辑:实际上我想要的是在我的控制器中设置 HttpServletResponse 对象的 ContentType。spring 是否为此提供了任何方法,而无需在控制器方法中获取 HttpServletResponse 对象作为参数? p>

【问题讨论】:

    标签: spring-mvc content-type


    【解决方案1】:

    我可以看到两个选项:

    如果您想要的内容类型是静态的,那么您可以将其添加到@RequestMapping,例如

    @RequestMapping(value="...", produces="text/plain")
    

    这只有在 HTTP 请求的 Accept 标头中包含相同的内容类型时才有效。见16.3.2.5 Producible Media Types

    或者,使用ResponseEntity,例如

    @RequestMapping("/something")
    public ResponseEntity<String> handle() {
      HttpHeaders responseHeaders = new HttpHeaders();
      responseHeaders.setContentType(new MediaType("text", "plain"));
      return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
    }
    

    MediaType 也有一些常见的 mime 类型定义为常量,例如MediaType.TEXT_PLAIN.

    16.3.3.6 Using HttpEntity&lt;?&gt;

    【讨论】:

    • 上述代码中的responseHeaders.setContentType("text/plain"); 行给出错误:setContentType(org.springframework.http.MediaType) in org.springframework.http.HttpHeaders cannot be applied to (java.lang.String)。所以我尝试了:responseHeaders.setContentType(new MediaType("text/plain")); 但这给出了错误:java.lang.IllegalArgumentException: Invalid token character '/' in token "text/plain"。有什么建议吗?
    • skaffman:我已经运行了您编辑的代码,现在出现错误:java.lang.NoSuchMethodError: org.springframework.http.HttpHeaders.readOnlyHttpHeaders(Lorg/springframework/http/HttpHeaders;)Lorg/springframework/http/HttpHeaders; org.springframework.http.HttpEntity.&lt;init&gt;(HttpEntity.java:100) org.springframework.http.HttpEntity.&lt;init&gt;(HttpEntity.java:70) org.springframework.http.HttpEntity.&lt;clinit&gt;(HttpEntity.java:58)
    【解决方案2】:

    只需将其作为参数传递,例如

    @RequestMapping( value="/test", method = RequestMethod.GET )
    public void test( HttpServletResponse response ) { ... }
    

    【讨论】:

    • 但这会将我的控制器绑定到我不想要的 Http API。请参阅我的编辑。
    【解决方案3】:

    我认为处理此问题的最佳方法是使用特定的View-Implementation,因为应该在此处进行响应呈现。

    【讨论】:

      猜你喜欢
      • 2015-03-10
      • 2011-08-28
      • 2012-04-20
      • 2010-12-12
      • 1970-01-01
      • 2011-11-23
      • 2019-03-03
      • 2016-12-05
      • 2017-09-17
      相关资源
      最近更新 更多