在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型标头 [英] In Spring MVC, how can I set the mime type header when using @ResponseBody

查看:42
本文介绍了在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 JSON 字符串的 Spring MVC 控制器,我想将 mimetype 设置为 application/json.我该怎么做?

I have a Spring MVC Controller that returns a JSON String and I would like to set the mimetype to application/json. How can I do that?

@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
    return myService.getJson();
}

业务对象已经可以作为 JSON 字符串使用,因此使用 MappingJacksonJsonView 不是我的解决方案.@ResponseBody 很完美,但是我该如何设置 mimetype?

The business objects are already available as JSON strings, so using MappingJacksonJsonView is not the solution for me. @ResponseBody is perfect, but how can I set the mimetype?

推荐答案

我会考虑重构服务以返回域对象而不是 JSON 字符串,并让 Spring 处理序列化(通过 MappingJacksonHttpMessageConverter当你写).从 Spring 3.1 开始,实现看起来非常简洁:

I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1, the implementation looks quite neat:

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
    method = RequestMethod.GET
    value = "/foo/bar")
@ResponseBody
public Bar fooBar(){
    return myService.getBar();
}

评论:

首先,@EnableWebMvc 必须是 已添加到您的应用程序配置中.

First, the <mvc:annotation-driven /> or the @EnableWebMvc must be added to your application config.

接下来,produces 注释的@RequestMapping 属性用于指定响应的内容类型.因此,它应该设置为 MediaType.APPLICATION_JSON_VALUE(或"application/json").

Next, the produces attribute of the @RequestMapping annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or "application/json").

最后,必须添加 Jackson,以便 Java 和 JSON 之间的任何序列化和反序列化将由 Spring 自动处理(Jackson 依赖项由 Spring 检测,MappingJacksonHttpMessageConverter 将在引擎盖下).

Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the MappingJacksonHttpMessageConverter will be under the hood).

这篇关于在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆