Managing custom Acccept header in Spring MVC

2019-02-27 09:53发布

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.

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

Any idea how to do it?

1条回答
成全新的幸福
2楼-- · 2019-02-27 09:55

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

查看更多
登录 后发表回答