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

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

问题描述

我有一个Spring MVC控制器返回一个JSON字符串,我想将mimetype设置为application / json。我如何做呢?

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

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

解决方案

我会考虑重构服务返回你的域对象,而不是JSON字符串,让Spring处理序列化(通过 MappingJacksonHttpMessageConverter )。从Spring 3.1开始,实现看起来很整齐:

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

注释:



首先,< mvc:annotation-driven /> @EnableWebMvc 必须添加到您的应用程序配置。 p>

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



最后,必须添加Jackson, Java和JSON之间的序列化和反序列化将由Spring自动处理(Jackson依赖由Spring检测, MappingJacksonHttpMessageConverter 将在底层)。


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();
}

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?

解决方案

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();
}

Comments:

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

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").

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天全站免登陆