Http Message Converters with the Spring Framework – 使用Spring框架的Http消息转换器

最后修改: 2014年 1月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll learn how to Configure HttpMessageConverters in Spring.

在本教程中,我们将学习如何在Spring中配置HttpMessageConverters

Simply put, we can use message converters to marshall and unmarshall Java Objects to and from JSON and XML over HTTP.

简单地说,我们可以使用消息转换器,通过HTTP将Java对象与JSON和XML进行汇总和解汇总。

2. The Basics

2.基础知识

2.1. Enable Web MVC

2.1.启用Web MVC

To start, the Web Application needs to be configured with Spring MVC support. A convenient and very customizable way to do this is to use the @EnableWebMvc annotation:

首先,Web应用程序需要被配置为支持Spring MVC。一种方便且非常可定制的方式是使用@EnableWebMvc 注解。

@EnableWebMvc
@Configuration
@ComponentScan({ "com.baeldung.web" })
public class WebConfig implements WebMvcConfigurer {
    
    // ...
    
}

Note that this class implements WebMvcConfigurer, which will allow us to change the default list of Http Converters with our own.

请注意,这个类实现了WebMvcConfigurer,,这将允许我们用我们自己的Http转换器的默认列表来改变。

2.2. The Default Message Converters

2.2.默认的消息转换器

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

默认情况下,下列HttpMessageConverters实例被预先启用:

  • 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.客户-服务器通信 – 仅限JSON

3.1. High-Level Content Negotiation

3.1.高级别的内容谈判

Each HttpMessageConverter implementation has one or several associated MIME Types.

每个HttpMessageConverter实现都有一个或几个相关的MIME类型。

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

当收到一个新的请求时,Spring将使用”Accept“头来确定它需要回应的媒体类型

It’ll then try to find a registered converter that’s capable of handling that specific media type. Finally, it’ll use this to convert the entity and send back the response.

然后,它将尝试找到一个能够处理该特定媒体类型的注册转换器。最后,它将使用这个转换器来转换实体并发回响应。

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

接收包含JSON信息的请求的过程类似。框架将使用”Content-Type“标头来确定请求体的媒体类型

Then it’ll search for a HttpMessageConverter that can convert the body sent by the client to a Java Object.

然后它会搜索一个HttpMessageConverter,可以将客户端发送的正文转换为一个Java对象。

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.
  • Then Spring uses one of the Jackson message converters to marshall the entities to JSON.

Now let’s look at the specifics of how this works, and how we can leverage the @ResponseBody and @RequestBody annotations.

现在让我们来看看这个工作的具体细节,以及我们如何利用@ResponseBody和@RequestBody注释。

3.2. @ResponseBody

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:

Controller方法上的@ResponseBody向Spring表明,该方法的返回值被直接序列化为HTTP响应的主体。如上所述,由客户端指定的”Accept“头将被用来选择适当的Http转换器来处理该实体。

@GetMapping("/{id}")
public @ResponseBody Foo findById(@PathVariable long id) {
    return fooService.findById(id);
}

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

现在客户端将在请求中指定 “接受 “头为application/json(例如,curl命令)。

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

The Foo class:

Foo类。

public class Foo {
    private long id;
    private String name;
}

And the HTTP Response Body:

以及HTTP响应体。

{
    "id": 1,
    "name": "Paul",
}

3.3. @RequestBody

3.3.@RequestBody

We can use the @RequestBody annotation on the argument of a Controller method to indicate that the body of the HTTP Request is deserialized to that particular Java entity. To determine the appropriate converter, Spring will use the “Content-Type” header from the client request: 

我们可以在控制器方法的参数上使用@RequestBody注解来表示HTTP请求的正文被反序列化为那个特定的Java实体。为了确定适当的转换器,Spring将使用客户端请求中的 “Content-Type “头。

@PutMapping("/{id}")
public @ResponseBody void update(@RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}

Next, we’ll consume this with a JSON object, specifying the “Content-Type to be application/json:

接下来,我们将用一个JSON对象来消费它,指定 “Content-Typeapplication/json

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

We’ll get back a 200 OK, a successful response:

我们会得到一个200 OK,一个成功的回应。

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

4.自定义转换器配置

We can also customize the message converters by implementing the WebMvcConfigurer interface and overriding the configureMessageConverters method:

我们还可以通过实现WebMvcConfigurer接口并重写configureMessageConverters方法来定制消息转换器。

@EnableWebMvc
@Configuration
@ComponentScan({ "com.baeldung.web" })
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        messageConverters.add(createXmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
    }

    private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
        MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();

        XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);

        return xmlConverter;
    } 
}

In this example, we’re creating a new converter, the MarshallingHttpMessageConverter, and 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.

在这个例子中,我们创建了一个新的转换器,MarshallingHttpMessageConverter,并使用Spring XStream支持来配置它。这允许有很大的灵活性,因为我们正在使用底层的Marshalling框架的低级API,在这种情况下是XStream,我们可以随意配置。

Note that this example requires adding the XStream library to the classpath.

注意,这个例子需要把XStream库添加到classpath。

Also be aware that by extending this support class, we’re losing the default message converters that were previously pre-registered.

还要注意的是,通过扩展这个支持类,我们将失去之前预注册的默认消息转换器。

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

当然,我们现在可以通过定义我们自己的MappingJackson2HttpMessageConverter.来为Jackson做同样的事情。我们可以在这个转换器上设置一个自定义的ObjectMapper,并让它按照我们的需要进行配置。

In this case, XStream was the selected marshaller/unmarshaller implementation, but others, like JibxMarshaller, can be used as well.

在这种情况下,XStream是被选中的marshaller/unmarshaller实现,但是其他,如JibxMarshaller,也可以使用。

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

在这一点上,由于后端启用了XML,我们可以用XML表示法来消费API。

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

4.1. Spring Boot Support

4.1.支持Spring Boot

If we’re using Spring Boot, we can avoid implementing the WebMvcConfigurer and adding all the Message Converters manually, as we did above.

如果我们使用Spring Boot,我们可以避免实现WebMvcConfigurer,并像上面那样手动添加所有的消息转换器。

We can just define different HttpMessageConverter beans in the context, and Spring Boot will add them automatically to the autoconfiguration that it creates:

我们只需在上下文中定义不同的HttpMessageConverter Bean,Spring Boot就会将它们自动添加到它所创建的自动配置中:

@Bean
public HttpMessageConverter<Object> createXmlHttpMessageConverter() {
    MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();

    // ...

    return xmlConverter;
}

5. Using Spring’s RestTemplate With HTTP Message Converters

5.使用Spring的RestTemplate与HTTP消息转换器

As well as on the server-side, HTTP Message Conversion can be configured on the client-side of the Spring RestTemplate.

除了在服务器端,HTTP消息转换也可以在Spring RestTemplate的客户端进行配置。

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

我们将在适当的时候用”Accept“和”Content-Type“头文件配置模板。然后,我们将尝试使用REST API,对Foo资源进行完整的编排和解编,包括JSON和XML。

5.1. Retrieving the Resource With No Accept Header

5.1.检索没有Accept头的资源

@Test
public void whenRetrievingAFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";

    RestTemplate restTemplate = new RestTemplate();
    Foo resource = restTemplate.getForObject(URI, Foo.class, "1");

    assertThat(resource, notNullValue());
}

5.2. Retrieving a Resource With application/xml Accept Header

5.2.用application/xml Accept头检索资源

Now let’s explicitly retrieve the Resource as an XML Representation. We’ll define a set of Converters and set these on the RestTemplate.

现在让我们明确地将资源检索为XML表示法。我们将定义一组转换器并在RestTemplate上设置这些转换器。

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

因为我们是在消费XML,所以我们将使用和以前一样的XStream marshaller。

@Test
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getXmlMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    ResponseEntity<Foo> response = 
      restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    Foo resource = response.getBody();

    assertThat(resource, notNullValue());
}

private List<HttpMessageConverter<?>> getXmlMessageConverters() {
    XStreamMarshaller marshaller = new XStreamMarshaller();
    marshaller.setAnnotatedClasses(Foo.class);
    MarshallingHttpMessageConverter marshallingConverter = 
      new MarshallingHttpMessageConverter(marshaller);

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(marshallingConverter);
    return converters;
}

5.3. Retrieving a Resource With application/json Accept Header

5.3.使用application/json Accept头检索资源

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

同样地,现在让我们通过要求JSON来消费REST API。

@Test
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getJsonMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(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<?>> getJsonMessageConverters() {
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new MappingJackson2HttpMessageConverter());
    return converters;
}

5.4. Update a Resource With XML Content-Type

5.4.用XML Content-Type更新资源

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

最后,我们将向REST API发送JSON数据,并通过Content-Type header指定该数据的媒体类型。

@Test
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getJsonAndXmlMessageConverters());

    Foo resource = new Foo("jason");
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType((MediaType.APPLICATION_XML));
    HttpEntity<Foo> entity = new HttpEntity<>(resource, headers);

    ResponseEntity<Foo> response = 
      restTemplate.exchange(URI, HttpMethod.POST, entity, Foo.class);
    Foo fooResponse = response.getBody();

    assertThat(fooResponse, notNullValue());
    assertEquals(resource.getName(), fooResponse.getName());
}

private List<HttpMessageConverter<?>> getJsonAndXmlMessageConverters() {
    List<HttpMessageConverter<?>> converters = getJsonMessageConverters();
    converters.addAll(getXmlMessageConverters());
    return converters;
}

What’s interesting here is that we’re able to mix the media types. We’re 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.

这里有趣的是,我们能够混合媒体类型。我们正在发送XML数据,但我们正在等待从服务器返回的JSON数据。这表明Spring的转换机制真的很强大。

6. Conclusion

6.结论

In this article, we learned 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’s so much more that the message conversion mechanism can do, as we can see from the last test example.

在这篇文章中,我们了解到Spring MVC如何允许我们指定和完全定制Http消息转换器,以自动将Java实体marshall/unmarshall到XML或JSON。当然,这只是一个简单的定义,消息转换机制能做的事情还有很多,我们可以从最后一个测试例子中看到。

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

我们还研究了如何通过RestTemplate客户端来利用同样强大的机制,从而形成一种完全类型安全的API消费方式。

As always, the code presented in this article is available over on GitHub.

一如既往,本文介绍的代码可在GitHub上获得over