Spring Boot 返回XML
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot 返回XML
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一般RESTful都是返回json,有時候可能需要返回xml,我們該如何操作呢?
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, "zsh"); }提交xml
同樣的,你也可以將xml請求自動轉換為實體:
@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = { "text/xml" }, produces = {"application/xml" })@ResponseBodypublic User post(@RequestBody User user) {return user;}JAXB相關的重要Annotation
@XmlRootElement:表示映射到根目錄標簽元素@XmlElement:表示映射到子元素@XmlAttribute:表示映射到屬性@XmlElementWrapper :表示類型是集合元素的子元素的上層目錄注:@XmlElementWrapper僅允許出現在集合屬性上。
UserControllerTest
public class UserControllerTest {@Testpublic 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);} }如果感覺不錯的話請給我點贊喲!!!
總結
以上是生活随笔為你收集整理的Spring Boot 返回XML的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言函数的概念
- 下一篇: Spring基于XML装配Bean