在Spring MVC中管理自定义Acccept标头 [英] Managing custom Acccept header in Spring MVC

查看:111
本文介绍了在Spring MVC中管理自定义Acccept标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Spring MVC开发的RESTful Web服务,无需任何配置,我可以从带有序列化为JSON的@ResponseBody带注释的控制器方法中返回对象.一旦未设置请求中的Accept标头或将其设置为application/json,此方法便会起作用.

I have a RESTful web service developed using Spring MVC and without any configuration I can return objects from my @ResponseBody annotated controller methods that get serialized to JSON. This works as soon as the Accept header in the request is not set or is application/json.

随着我受到GitHub API规范的启发,我想为我的API实现自定义的mime类型为

As I'm getting inspired by the GitHub API specification, I wanted to implement custom mime type for my API as GitHub does, for example: application/vnd.myservice+json. But then I need to tell Spring MVC that my controllers can provide this mime type and that it should be serialized by Json (i.e org.springframework.web.servlet.view.json.MappingJacksonJsonView class).

有什么想法吗?

推荐答案

您可能可以完全使用org.springframework.http.converter.json.MappingJacksonHttpMessageConverter进行操作.由于它不是最后一堂课,因此您可以通过以下方式从该类派生您的转换器:

You can probably do exactly what is being done with org.springframework.http.converter.json.MappingJacksonHttpMessageConverter. Since it is not a final class, you can derive your converter from this one this way:

class MyCustomVndConverter extends MappingJacksonHttpMessageConverter{
    public MyCustomVndConverter (){
        super(MediaType.valueOf("application/vnd.myservice+json"));
    }
}

然后以这种方式注册您的转换器:

then register your converter this way:

<mvc:annotation-driven> 
   <mvc:message-converters register-defaults="true">
       <bean class="MyCustomVndConverter "/>
   </mvc:message-converters>
</mvc:annotation-driven>

它应该可以处理这些更改

It should just work with these changes

这篇关于在Spring MVC中管理自定义Acccept标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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