Spring Boot returns XML

Posted by POGRAN on Tue, 18 Feb 2020 04:40:45 +0100

In general, RESTful is to return json. Sometimes it may be necessary to return xml. What should we do?

Jackson

Maven adds jar file import

<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
   <groupId>org.codehaus.woodstox</groupId>
   <artifactId>woodstox-core-asl</artifactId>
   <version>4.1.0</version>
</dependency>
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

Model object

@JacksonXmlRootElement(localName = "user")
public class User {
  private Long id;
  @JacksonXmlCData
  @JacksonXmlProperty(localName = "Content")
  private String content;

Explanatory notes

@There is a localName attribute in the Jackson xmlrootelement annotation. If this attribute is not set, the outermost XML generated is
 < user > < user > instead of < user > < user >

@The Jackson xmlcdata annotation is for generating

<![CDATA[text]]>
This kind of data, if you don't need it, can be removed

@The Jackson xmlproperty annotation is usually not required, but if you want your xml node name, capitalize it. For example, the content in the example must be annotated, and the local name of the annotation must be filled with the node name you want. most important of all! The original attribute content of entity class must be lowercase! Otherwise, it will be recognized as two different attributes.

With the above configuration, when the Controller returns the entity class, it will transform the entity class into an xml object just like converting Json. Sometimes your browser does not recognize xml because the content type you return is not xml. You can modify it by modifying the products attribute of the @ RequestMapping annotation

Output xml

@RequestMapping(value = "/user", method = RequestMethod.GET, produces = { "application/xml" })
@ResponseBody
public User user() {
  return new User(1L, "zsh");
}

Submit xml

Similarly, you can automatically convert xml requests to entities:

@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = { "text/xml" }, produces = {
      "application/xml" })
  @ResponseBody
  public User post(@RequestBody User user) {
    return user;
  }

Important annotations related to JAXB

	@XmlRootElement: represents a mapping to a root label element
	
	@XmlElement: representation mapped to child element
	
	@XmlAttribute: representation mapped to attribute
	
	@XmlElementWrapper: indicates the upper directory where the type is a child element of a collection element

Note: @ XmlElementWrapper is only allowed on collection properties.

UserControllerTest

public class UserControllerTest {

  @Test
  public void testPost() throws Exception {
    // Direct string splicing
    StringBuilder builder = new StringBuilder();
    // xml data storage
    builder.append("<user><id>1</id><Content>JE-GE</Content></user>");
    String data = builder.toString();
    System.out.println(data);
    String url = "http://localhost:8080/user";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(data, "text/xml", "utf-8"));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String content = EntityUtils.toString(entity);
    System.out.println("content:" + content);
  }
}

If you feel good, please give me some praise!!!

281 original articles published, 91 praised, 10000 visitors+
Private letter follow

Topics: xml Attribute JSON Maven