Spring Boot 菜鳥教程 24 返回XML
阿新 • • 發佈:2018-12-31
GitHub
需求產生
一般RESTful都是返回json,有時候可能需要返回xml,那又怎樣操作呢?
方案1-Jackson
Maven增加jar檔案匯入
<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>
模型物件
@JacksonXmlRootElement (localName = "user")
public class User {
private Long id;
@JacksonXmlCData
@JacksonXmlProperty(localName = "Content")
private String content;
註解說明
@JacksonXmlRootElement註解中有localName屬性,該屬性如果不設定,那麼生成的XML最外面就是
<User></User>,而不是<user></user>
@JacksonXmlCData註解是為了生成
<![CDATA[text]]>
這樣的資料,如果你不需要,可以去掉
@JacksonXmlProperty註解通常可以不需要,但是如果你想要你的xml節點名字,首字母大寫。比如例子中的Content,那麼必須加這個註解,並且註解的localName填上你想要的節點名字。最重要的是!實體類原來的屬性content必須首字母小寫!否則會被識別成兩個不同的屬性。
有了上面的配置,在Controller返回實體類的時候,就會像轉換Json一樣,將實體類轉換為xml物件了。有時候你的瀏覽器並不能識別xml,是因為你返回的content-type不是xml,可以通過修改@RequestMapping註解的produces屬性來修改:
輸出xml
@RequestMapping(value = "/user", method = RequestMethod.GET, produces = { "application/xml" })
@ResponseBody
public User user() {
return new User(1L, "JE-GE");
}
提交xml
同樣的,你也可以將xml請求自動轉換為實體:
@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = { "text/xml" }, produces = {
"application/xml" })
@ResponseBody
public User post(@RequestBody User user) {
return user;
}
JAXB相關的重要Annotation
@XmlRootElement:表示對映到根目錄標籤元素
@XmlElement:表示對映到子元素
@XmlAttribute:表示對映到屬性
@XmlElementWrapper :表示型別是集合元素的子元素的上層目錄
注:@XmlElementWrapper僅允許出現在集合屬性上。
UserControllerTest
/**
* @author JE哥
* @email [email protected]
* @description:
*/
public class UserControllerTest {
@Test
public void testPost() throws Exception {
// 直接字串拼接
StringBuilder builder = new StringBuilder();
// xml資料儲存
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);
}
}
方案2等待
原始碼地址
如果覺得我的文章或者程式碼對您有幫助,可以請我喝杯咖啡。
您的支援將鼓勵我繼續創作!謝謝!