Spring boot 2. X Basics: how to extend requests and responses in XML format
Program description DD 2021-06-25 01:52:12

All before Spring Boot tutorial , We all mentioned and used only for HTML and JSON Format request and response processing . So for XML How to make requests in the format of Controller Packaging into objects , And how to XML Return an object in the format of ?

Realization principle : Message converter (Message Converter)

Before extending the above question , We need to know Spring Boot In dealing with HTTP The request is implemented using Spring MVC. And in the Spring MVC There is a message converter concept in , It is mainly responsible for processing request data in various formats , To convert a package into an object , To provide a better programming experience .

stay Spring MVC It defines HttpMessageConverter Interface , Abstracts the message converter's judgment of type 、 The judgment and operation of reading and writing , We can see the following definition :

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 everyone knows ,HTTP Requested Content-Type There are different format definitions , If you want to support Xml Format message conversion , You have to use the corresponding converter .Spring MVC By default, there is already a set of Jackson The converter implemented MappingJackson2XmlHttpMessageConverter.

Extended implementation

First step : introduce Xml Message converter

In tradition Spring Application , We can add a pair of Xml Message transformation of format data :

@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()));
}
}

stay Spring Boot Applications don't have to be as cumbersome as above , Just add jackson-dataformat-xml rely on ,Spring Boot It will automatically introduce MappingJackson2XmlHttpMessageConverter The implementation of the :

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

meanwhile , For configuration Xml The annotations used to maintain the relationship between data and object properties are also in the above dependency , So this dependence is also necessary .

The second step : Define objects and Xml The relationship between

After completing the basic expansion , Now you can define Xml The content corresponds to Java Object , such as :

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

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

}

among :@Data@NoArgsConstructor@AllArgsConstructor yes lombok Simplified code annotations , Mainly used to generate get、set And constructors .@JacksonXmlRootElement@JacksonXmlProperty Annotations are used to maintain object properties xml Correspondence in .

Of the above configuration User object , It can be mapped to Xml A sample of ( You can use the above xml To request the interface ):

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

The third step : Create receive xml Requested interface

After completing the object to be converted , You can write an interface to receive xml And back to 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;
}

}

Last , start-up Spring Boot application , adopt POSTMAN And so on , Try this interface , You can see the request Xml, And it returns the processed Xml Content .

This series of tutorials 《Spring Boot 2.x Basic course 》 Click through !. If you encounter difficulties in the process of learning , It is suggested to join Spring Technology exchange group , Participate in communication and discussion , Better learning and progress !

Code example

For an example of this article, see the following in the warehouse chapter2-8 Catalog :

If you think this article is good , welcome Star Support , Your concern is the driving force of my persistence !

Please bring the original link to reprint ,thank
Similar articles