2

In all previous Spring Boot tutorials, we only mentioned and used request and response processing for HTML and JSON formats. So how to quickly wrap requests in XML format into objects in Controller, and how to return an object in XML format?

Implementation principle: Message Converter

Before extending the above questions, we must first know that the implementation of HTTP request processing in Spring Boot is Spring MVC. In Spring MVC, there is the concept of a message converter, which is mainly responsible for processing request data in various formats and converting packets into objects to provide a better programming experience.

HttpMessageConverter interface is defined in Spring MVC, which abstracts the message converter's judgment of type, judgment and operation of reading and writing. The specific definition can be seen as follows:

public interface HttpMessageConverter<T> {

    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

    List<MediaType> getSupportedMediaTypes();

    T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;

    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;

}

As we all know, the Content-Type of the HTTP request has a variety of different format definitions. If you want to support the message conversion in the Xml format, you must use the corresponding converter. By default, Spring MVC has a set of converters MappingJackson2XmlHttpMessageConverter implemented by Jackson.

Extension implementation

first step: the introduction of Xml message converter

In traditional Spring applications, we can add message conversion to Xml format data through the following configuration:

@Configuration
public class MessageConverterConfig1 extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
        builder.indentOutput(true);
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
    }
}

In the Spring Boot application, there is no need to be as troublesome as above, just add the jackson-dataformat-xml dependency, and Spring Boot will automatically introduce the implementation of MappingJackson2XmlHttpMessageConverter

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

At the same time, the annotations to be used in order to configure the relationship between the Xml data and the maintenance of the object properties are also in the above dependencies, so this dependency is also necessary.

Step 2: Define the relationship between the object and Xml

After completing the basic extension, the Java object corresponding to the Xml content can be defined below, such as:

@Data
@NoArgsConstructor
@AllArgsConstructor
@JacksonXmlRootElement(localName = "User")
public class User {

    @JacksonXmlProperty(localName = "name")
    private String name;
    @JacksonXmlProperty(localName = "age")
    private Integer age;

}

Among them: @Data , @NoArgsConstructor , @AllArgsConstructor are the annotations of lombok simplified code, mainly used to generate get, set and constructor functions. @JacksonXmlRootElement annotations 060d59b253bf00 and @JacksonXmlProperty are used to maintain the correspondence between object attributes in xml.

For the User object configured above, the Xml that can be mapped is as follows (you can use the above xml to request the interface later):

<User>
    <name>aaaa</name>
    <age>10</age>
</User>

Step 3: Create an interface

After completing the object to be converted, you can write an interface to receive xml and return xml, such as:

@Controller
public class UserController {

    @PostMapping(value = "/user", 
        consumes = MediaType.APPLICATION_XML_VALUE, 
        produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public User create(@RequestBody User user) {
        user.setName("didispace.com : " + user.getName());
        user.setAge(user.getAge() + 100);
        return user;
    }

}

Finally, start the Spring Boot application, try this interface through a request tool such as POSTMAN, you can see the request Xml, and return the processed Xml content.

This series of tutorials "Spring Boot 2.x Basic Tutorial" click directly! . If you encounter difficulties in the learning process, it is recommended to join Spring Technical Exchange Group , participate in exchanges and discussions, and better study and progress!

Code example

For related examples in this article, you can view the chapter2-8 directory in the following warehouse:

If you think this article is good, welcome Star support, your attention is my motivation for persistence!

Welcome to pay attention to my public account: Program Ape DD, share knowledge and thoughts that can’t be seen elsewhere

程序猿DD
2.2k 声望2.8k 粉丝

作品:《Spring Cloud微服务实战》、SpringForAll社区、OpenWrite、Youtube中文配音