【发布时间】:2012-01-19 14:50:22
【问题描述】:
如何在我的 spring 控制器中的方法中获取 HttpServletResponse object以便我的应用程序与 Http API 保持松散耦合?
谢谢...
编辑:实际上我想要的是在我的控制器中设置 HttpServletResponse 对象的 ContentType。spring 是否为此提供了任何方法,而无需在控制器方法中获取 HttpServletResponse 对象作为参数? p>
【问题讨论】:
如何在我的 spring 控制器中的方法中获取 HttpServletResponse object以便我的应用程序与 Http API 保持松散耦合?
谢谢...
编辑:实际上我想要的是在我的控制器中设置 HttpServletResponse 对象的 ContentType。spring 是否为此提供了任何方法,而无需在控制器方法中获取 HttpServletResponse 对象作为参数? p>
【问题讨论】:
我可以看到两个选项:
如果您想要的内容类型是静态的,那么您可以将其添加到@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.
【讨论】:
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"。有什么建议吗?
java.lang.NoSuchMethodError: org.springframework.http.HttpHeaders.readOnlyHttpHeaders(Lorg/springframework/http/HttpHeaders;)Lorg/springframework/http/HttpHeaders; org.springframework.http.HttpEntity.<init>(HttpEntity.java:100) org.springframework.http.HttpEntity.<init>(HttpEntity.java:70) org.springframework.http.HttpEntity.<clinit>(HttpEntity.java:58)。
只需将其作为参数传递,例如
@RequestMapping( value="/test", method = RequestMethod.GET )
public void test( HttpServletResponse response ) { ... }
【讨论】:
我认为处理此问题的最佳方法是使用特定的View-Implementation,因为应该在此处进行响应呈现。
【讨论】: