springmvc怎么设置相应头信息

 我来答
xiangjuan314
2016-06-19 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2933万
展开全部
我们知道response 的content type主要有:
text/html
text/plain
application/json;charset=UTF-8
application/octet-stream

先举一个例子,spring mvc中可以通过如下方式返回json字符串:
Java代码
@ResponseBody
@RequestMapping(value = "/upload")
public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)
throws IOException {
String content = null;
Map map = new HashMap();
ObjectMapper mapper = new ObjectMapper();

map.put("fileName", "a.txt");
try {
content = mapper.writeValueAsString(map);
System.out.println(content);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return content;

}
虽然访问时返回的确实是json字符串,但是response 的content type是"

text/html

"这不是我们期望的,我们期望的response content type是"application/json"或者"application/json;charset=UTF-8",那么如何实现呢?
通过注解@RequestMapping 中的produces
用法如下:
Java代码
@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")
spring MVC官方文档:
Producible Media Types
You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:
@Controller@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")@ResponseBodypublic Pet getPet(@PathVariable String petId, Model model) { // implementation omitted}

Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.
Tip

The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式