Home  >  Article  >  Java  >  Introduction to methods to extend support for XML requests and responses in Spring Boot

Introduction to methods to extend support for XML requests and responses in Spring Boot

不言
不言Original
2018-09-27 16:02:242489browse

This article brings you an introduction to the method of extending XML request and response support in Spring Boot. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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

Implementation principle: Message Converter

Before expanding on the above issues, we must first know that the implementation of HTTP requests in Spring Boot uses Spring MVC. There is a concept of message converter in Spring MVC, which is mainly responsible for processing request data in various formats and converting it into objects to provide a better programming experience.

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

public interface HttpMessageConverter<t> {

    boolean canRead(Class> clazz, [@Nullable](https://my.oschina.net/u/2896689) MediaType mediaType);

    boolean canWrite(Class> clazz, [@Nullable](https://my.oschina.net/u/2896689) MediaType mediaType);

    List<mediatype> getSupportedMediaTypes();

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

    void write(T t, [@Nullable](https://my.oschina.net/u/2896689) MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;

}</mediatype></t>

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

Extended implementation

Step one: Introduce the Xml message converter

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

@Configuration
public class MessageConverterConfig1 extends WebMvcConfigurerAdapter {
    [@Override](https://my.oschina.net/u/1162528)
    public void configureMessageConverters(List<httpmessageconverter>> converters) {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
        builder.indentOutput(true);
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
    }
}</httpmessageconverter>

In Spring Boot application, you don’t need to be as troublesome as above. You only need to add 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, in order to configure Xml data The annotations used to maintain the relationship between object attributes 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, you can define the Java object corresponding to the Xml content, 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 annotations for lombok to simplify the code, mainly used to generate get, set and constructor functions. The @JacksonXmlRootElement and @JacksonXmlProperty annotations are used to maintain the correspondence between object attributes in xml.

The User object configured above, the Xml sample 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 to receive xml requests

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 and try this interface through request tools such as POSTMAN. You can see that the Xml is requested and the processed Xml content is returned. (Case Code)

Introduction to methods to extend support for XML requests and responses in Spring Boot

The above is the detailed content of Introduction to methods to extend support for XML requests and responses in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn