日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

Spring Boot 返回XML

發(fā)布時間:2025/3/12 asp.net 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot 返回XML 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一般RESTful都是返回json,有時候可能需要返回xml,我們該如何操作呢?

Jackson

Maven增加jar文件導(dǎo)入

<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注解中有l(wèi)ocalName屬性,該屬性如果不設(shè)置,那么生成的XML最外面就是 <User></User>,而不是<user></user>@JacksonXmlCData注解是為了生成<![CDATA[text]]> 這樣的數(shù)據(jù),如果你不需要,可以去掉@JacksonXmlProperty注解通常可以不需要,但是如果你想要你的xml節(jié)點名字,首字母大寫。比如例子中的Content,那么必須加這個注解,并且注解的localName填上你想要的節(jié)點名字。最重要的是!實體類原來的屬性content必須首字母小寫!否則會被識別成兩個不同的屬性。有了上面的配置,在Controller返回實體類的時候,就會像轉(zhuǎn)換Json一樣,將實體類轉(zhuǎn)換為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請求自動轉(zhuǎn)換為實體:

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

JAXB相關(guān)的重要Annotation

@XmlRootElement:表示映射到根目錄標(biāo)簽元素@XmlElement:表示映射到子元素@XmlAttribute:表示映射到屬性@XmlElementWrapper :表示類型是集合元素的子元素的上層目錄

注:@XmlElementWrapper僅允許出現(xiàn)在集合屬性上。

UserControllerTest

public class UserControllerTest {@Testpublic void testPost() throws Exception {// 直接字符串拼接StringBuilder builder = new StringBuilder();// xml數(shù)據(jù)存儲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);} }

如果感覺不錯的話請給我點贊喲!!!

總結(jié)

以上是生活随笔為你收集整理的Spring Boot 返回XML的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。