In all the previous Spring Boot tutorials, we have only mentioned and used request and response processing for HTML and JSON formats. So how do you quickly wrap an XML request into an object in Controller, and how do you return an object in XML?
Implementation principle: Message Converter
Before we extend the above, we need to know that the implementation in Spring Boot that handles HTTP requests uses Spring MVC. In Spring MVC, there is the concept of a message converter, which is responsible for processing request data in various formats and converting packages into objects to provide a better programming experience.
The HttpMessageConverter interface is defined in Spring MVC, which abstracts the judgment of the message converter on the type, the judgment and operation of the read and write, as shown in the following definition:
public interface HttpMessageConverter<T> {
boolean canRead(Class<? > clazz,@Nullable MediaType mediaType);
boolean canWrite(Class<? > clazz,@Nullable MediaType mediaType);
List<MediaType> getSupportedMediaTypes(a);
T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}
Copy the code
It is well known that the CONTent-Type of AN HTTP request is defined in a variety of different formats, and if you want to support xmL-formatted message transformation, you must use the corresponding converter. In the Spring MVC has a set of Jackson was adopted to realize converter MappingJackson2XmlHttpMessageConverter by default.
The extension implementation
Step 1: Introduce Xml message converters
In traditional Spring applications, we can add message conversion to Xml data with the following configuration:
@Configuration
public class MessageConverterConfig1 extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List
> converters)
> {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
builder.indentOutput(true);
converters.add(newMappingJackson2XmlHttpMessageConverter(builder.build())); }}Copy the code
In the Spring the Boot applications need not so trouble as above, only need to add Jackson – dataformat – XML dependence, Spring Boot automatically introduced MappingJackson2XmlHttpMessageConverter implementation:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Copy the code
Also, the annotations used to configure the relationship between the Xml data and the object attributes are in the dependency, so this dependency is also required.
Step 2: Define the relationship between the object and Xml
With basic extensions in place, you can now define Java objects that correspond to 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;
}
Copy the code
Where: @data, @noargsconstructor, and @Allargsconstructor are annotations to Lombok’s simplified code for generating get, set, and constructor functions. The @JacksonXmlRootelement and @JacksonXmlProperty annotations are used to maintain the mapping of object attributes in XML.
An example of the Xml that can be mapped to the User object configured above (the above Xml can be used later to request the interface) is as follows:
<User>
<name>aaaa</name>
<age>10</age>
</User>
Copy the code
Step 3: Create an interface to receive XML requests
After completing the object to be transformed, 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);
returnuser; }}Copy the code
Finally, start the Spring Boot application and try out the interface through request tools like POSTMAN. You can see the request Xml and return the processed Xml content.
Spring Boot 2.x Basic Tutorial . If you encounter difficulties during the learning process, it is recommended to join the Spring Technology Exchange group to participate in the exchange and discussion, so as to better learn and progress!
Code sample
For an example of this article, see the chapter2-8 directory in the repository below:
- Github:github.com/dyc87112/Sp…
- Gitee:gitee.com/didispace/S…
If you found this article good, welcomeStar
Support, your attention is my motivation!
Welcome to pay attention to my public account: program ape DD, share the outside can not see the dry goods and thinking!