不使用HttpServletResponse设置响应内容类型 [英] Setting the response content-type without using HttpServletResponse
问题描述
如何在spring控制器的方法中获取 HttpServletResponse对象
,以便我的应用程序保持与Http API的松散耦合?
How can I get HttpServletResponse object
in a method in my spring controller so that my application remains loosely coupled with Http API?
谢谢...
编辑:实际上,我要设置的 ContentType spring中的HttpServletResponse对象是否可以提供任何方法,而无需在控制器方法中将HttpServletResponse对象作为参数?
Actually what i want is to set the ContentType of the HttpServletResponse object in my controller.Does spring provides any way for this without getting HttpServletResponse object as argument in the method of controller?
推荐答案
我可以看到两个选项:
如果所需的内容类型是静态的,则可以将其添加到 @RequestMapping
,例如
If the content-type that you want is static, then you can add it to @RequestMapping
, e.g.
@RequestMapping(value="...", produces="text/plain")
仅当HTTP请求的 Accept $ c $包含相同的内容类型时,此选项才有效c>标头,不过。参见 16.3.2.5可生产媒体类型。
This will only work if the HTTP request contains the same content-type in its Accept
header, though. See 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
。
MediaType
also has a handful of common mime types defined as constants, e.g. MediaType.TEXT_PLAIN
.
这篇关于不使用HttpServletResponse设置响应内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!