原文:http://www.baeldung.com/spring-httpmessageconverter-rest

1. Overview

This article describes how to Configure HttpMessageConverter in Spring.

Simply put, message converters are used to marshall and unmarshall Java Objects to and from JSON, XML, etc – over HTTP.

2. The Basics

2.1. Enable Web MVC

The Web Application needs to be configured with Spring MVC support – one convenient and very customizable way to do this is to use the @EnableWebMvc annotation:

1
2
3
4
5
6
@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}

Note that this class extends WebMvcConfigurerAdapter – which will allow us to change the default list of Http Converters with our own.

2.2. The Default Message Converters

By default, the following HttpMessageConverters instances are pre-enabled:

  • ByteArrayHttpMessageConverter – converts byte arrays
  • StringHttpMessageConverter – converts Strings
  • ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
  • SourceHttpMessageConverter – converts javax.xml.transform.Source
  • FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
  • Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
  • MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)
  • MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
  • AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
  • RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)

3. Client-Server Communication – JSON only

3.1. High Level Content Negotiation

Each HttpMessageConverter implementation has one or several associated MIME Types.

When receiving a new request, Spring will use of the “Accept” header to determine the media type that it needs to respond with.

It will then try to find a registered converter that is capable of handling that specific media type – and it will use it to convert the entity and send back the response.

The process is similar for receiving a request which contains JSON information – the framework will use  the “Content-Type” header to determine the media type of the request body.

It will then search for a HttpMessageConverter that can convert the body sent by the client to a Java Object.

Let’s clarify this with a quick example:

  • the Client sends a GET request to /foos with the Accept header set to application/json – to get all Foo resources as Json
  • the Foo Spring Controller is hit and returns the corresponding Foo Java entities
  • Spring then uses one of the Jackson message converters to marshall the entities to json

Let’s now look at the specifics of how this works – and how we should leverage the@ResponseBody and @RequestBody annotations.

3.2. @ResponseBody

@ResponseBody on a Controller method indicates to Spring that the return value of the method is serialized directly to the body of the HTTP Response. As discussed above, the “Accept” header specified by the Client will be used to choose the appropriate Http Converter to marshall the entity.

Let’s look at a simple example:

1
2
3
4
@RequestMapping(method=RequestMethod.GET, value="/foos/{id}")
public @ResponseBody Foo findById(@PathVariable long id) {
    return fooService.get(id);
}

Now, the client will specify the “Accept” header to application/json in the request – example curl command:

curl --header "Accept: application/json" http://localhost:8080/spring-rest/foos/1

The Foo class:

1
2
3
4
public class Foo {
    private long id;
    private String name;
}

And the Http Response Body:

1
2
3
4
{
    "id": 1,
    "name": "Paul",
}

3.3. @RequestBody

@RequestBodyis used on the argument of a Controller method – it indicates to Spring that the body of the HTTP Request is deserialized to that particular Java entity. As discussed previously, the “Content-Type” header specified by the Client will be used to determine the appropriate converter for this.

Let’s look at an example:

1
2
3
4
@RequestMapping(method=RequestMethod.PUT, value="/foos/{id}")
public @ResponseBody void updateFoo(@RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}

Now, let’s consume this with a JSON object – we’re specifying “Content-Type” to beapplication/json:

curl -i -X PUT -H "Content-Type: application/json" 
-d '{"id":"83","name":"klik"}' http://localhost:8080/spring-rest/foos/1

We get back a 200 OK – a successful response:

1
2
3
4
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Fri, 10 Jan 2014 11:18:54 GMT

4. Custom Converters Configuration – adding XML Support

We can customize the message converters by extending the WebMvcConfigurerAdapter class and overriding the configureMessageConvertersmethod:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        messageConverters.add(createXmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
 
        super.configureMessageConverters(converters);
    }
    private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
        MarshallingHttpMessageConverter xmlConverter =
          new MarshallingHttpMessageConverter();
 
        XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);
 
        return xmlConverter;
    }
}

Note that the XStream library now needs to be present on the classpath.

Also be aware that by extending this support class, we are losing the default message converters which were previously pre-registered – we only have what we define.

Let’s go over this example – we are creating a new converter – theMarshallingHttpMessageConverter – and we’re using the Spring XStream support to configure it. This allows a great deal of flexibility since we’re working with the low level APIs of the underlying marshalling framework – in this case XStream – and we can configure that however we want.

We can of course now do the same for Jackson – by defining our ownMappingJackson2HttpMessageConverter we can now set a custom ObjectMapper on this converter and have it configured as we need to.

In this case XStream was the selected marshaller/unmarshaller implementation, but others like CastorMarshaller can be used to – refer to Spring api documentation for full list of available marshallers.

At this point – with XML enabled on the back end – we can consume the API with XML Representations:

1
curl --header "Accept: application/xml" http://localhost:8080/spring-rest/foos/1

5. Using Spring’s RestTemplate with Http Message Converters

As well as with the server side, Http Message Conversion can be configured in the client side on the Spring RestTemplate.

We’re going to configure the template with the “Accept” and “Content-Type” headers when appropriate and we’re going to try to consume the REST API with full marshalling and unmarshalling of the Foo Resource – both with JSON and with XML.

5.1. Retrieving the Resource with no Accept Header

1
2
3
4
5
6
7
@Test
public void testGetFoo() {
      String URI = “http://localhost:8080/spring-rest/foos/{id}";
      RestTemplate restTemplate = new RestTemplate();
      Foo foo = restTemplate.getForObject(URI, Foo.class, "1");
      Assert.assertEquals(new Integer(1), foo.getId());
}

5.2. Retrieving a Resource with application/xml Accept header

Let’s now explicitly retrieve the Resource as an XML Representation – we’re going to define a set of Converters – same way we did previously – and we’re going to set these on the RestTemplate.

Because we’re consuming XML, we’re going to use the same XStream marshaller as before:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());
 
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
 
    ResponseEntity<Foo> response =
      restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    Foo resource = response.getBody();
 
    assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getMessageConverters() {
    XStreamMarshaller marshaller = new XStreamMarshaller();
    MarshallingHttpMessageConverter marshallingConverter =
      new MarshallingHttpMessageConverter(marshaller);
    converters.add(marshallingConverter);
1
2
3
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    return converters;
}

5.3. Retrieving a Resource with application/json Accept header

Similarly, let’s now consume the REST API by asking for JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";
 
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());
 
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
 
    ResponseEntity<Foo> response =
      restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    Foo resource = response.getBody();
 
    assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new MappingJackson2HttpMessageConverter());
    return converters;
}

5.4. Update a Resource with XML Content-Type

Finally, let’s also send JSON data to the REST API and specify the media type of that data via the Content-Type header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());
 
    Foo resource = new Foo(4, "jason");
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType((MediaType.APPLICATION_XML));
    HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers);
 
    ResponseEntity<Foo> response =
      restTemplate.exchange(URI, HttpMethod.PUT, entity, Foo.class, resource.getId());
    Foo fooResponse = response.getBody();
 
    Assert.assertEquals(resource.getId(), fooResponse.getId());
}

What’s interesting here is that we’re able to mix the media types – we are sending XML data but we’re waiting for JSON data back from the server. This shows just how powerful the Spring conversion mechanism really is.

6. Conclusion

In this tutorial, we looked at how Spring MVC allows us to specify and fully customize Http Message Converters to automatically marshall/unmarshall Java Entities to and from XML or JSON. This is of course a simplistic definition, and there is so much more that the message conversion mechanism can do – as we can see from the last test example.

We have also looked at how to leverage the same powerful mechanism with theRestTemplate client – leading to a fully type-safe way of consuming the API.

Http Message Converters with the Spring Framework--转载的更多相关文章

  1. Spring Framework(框架)整体架构 变迁

    Spring Framework(框架)整体架构 2018年04月24日 11:16:41 阅读数:1444 标签: Spring框架架构 更多 个人分类: Spring框架   版权声明:本文为博主 ...

  2. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块

    spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...

  3. Spring Framework 5.0.0.M3中文文档 翻译记录 Part I. Spring框架概览1-2.2

    Part I. Spring框架概览 The Spring Framework is a lightweight solution and a potential one-stop-shop for ...

  4. Spring系列(零) Spring Framework 文档中文翻译

    Spring 框架文档(核心篇1和2) Version 5.1.3.RELEASE 最新的, 更新的笔记, 支持的版本和其他主题,独立的发布版本等, 是在Github Wiki 项目维护的. 总览 历 ...

  5. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(一)

    题外话:本篇是对之前那篇的重排版.并拆分成两篇,免得没了看的兴趣. 前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的 ...

  6. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(二)

    接前一篇 Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 本篇主要内容:Spring Type Conver ...

  7. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion

    本篇太乱,请移步: Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 写了删删了写,反复几次,对自己的描述很不 ...

  8. Spring Framework 官方文档学习(一)介绍

    http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#overview-maven-bom ...

  9. Dive into Spring framework -- 了解基本原理(一)

    在继续我们的分析之前,推荐各位静心来读一下<<Expert_OneOne_J2EE_Design_and_Development>> 第四章, 正如spring BeanFac ...

随机推荐

  1. 游戏设计模式:Subclass Sandbox模式,以及功能方法集的设计思考

    书中总结出这种 Subclass Sandbox 的设计模式 Game Design Patterns: Subclass Sandbox 这种模式要点有两点: 在基类中实现各种功能性方法供子类调用 ...

  2. 今天工作遇到要发短信(ios)的功能,于是随手记录了一下

    ios中发送短信有两种 1.程序外调用系统短信 2.程序内调用系统发短信 第一种比较简单,直接调用url就可以了 oc下的代码为 [[UIApplication sharedApplication] ...

  3. 2016年CCF第七次测试 俄罗斯方块

    //2016年CCF第七次测试 俄罗斯方块 // 这道小模拟题还是不错 // 思路:处理出输入矩阵中含1格子的行数和列数 // 再判是否有一个格子碰到底部,否则整体再往下移动一步,如果有一个格子不能移 ...

  4. Tasks Queues and Cron Jobs(任务队列和时钟守护作业)

    一个网络应用必须迅速响应网络请求,一般要小于1s,最好是几十微秒,以便为坐在浏览器前面的用户提供一个流畅的体验.这就给不了应用太多的时间来处理工作.有时会是有更多的工作要做而不是有时间来做它.< ...

  5. 对ArrayList 进行深拷贝

    ArrayList arr = new ArrayList(); arr.Add()); arr.Add()); arr.Add()); ArrayList arr2 = new ArrayList( ...

  6. homework-08

    这次作业是考察关于C++的一些使用,由于我的C++只掌握了基本功,所以我只有霸王硬上弓,勉强写写自己的浅见. 1. 理解C++变量的作用域和生命周期 对一个C++变量来说,有两个属性非常重要:作用域和 ...

  7. 现代程序设计——homework-10

    设计 对于MVC我的理解是这样的,V是台显示器,注意仅仅是一台比显示器普通显示器多几个按钮,用户按什么,按了什么该干什么都不用操心:M是实体的软件抽象,假设实体可以但不执行,我就可以一步一步走,实体可 ...

  8. POJ 2421 Constructing Roads (最小生成树)

    Constructing Roads 题目链接: http://acm.hust.edu.cn/vjudge/contest/124434#problem/D Description There ar ...

  9. codeforces 630R Game

    R. Game time limit per test 0.5 seconds memory limit per test 64 megabytes input standard input outp ...

  10. 转载 C#结构体(struct)和类(class)的区别

    转载原地址: http://dotnet.9sssd.com/csbase/art/8 C#结构体和类的区别问题:在C#编程语言中,类属于引用类型的数据类型,结构体属于值类型的数据类型,这两种数据类型 ...