springMVC xml與實體對象的互轉
阿新 • • 發佈:2018-05-22
springMVC xmlRequestMapping註解
consumes 設置請求的數據格式最終httpMessageConverter根據consumes的響應media-type來選擇對應的轉換類。
@PostMapping(value = "/testXmlRequest",
produces = "application/xml; charset=UTF-8",
consumes = "application/xml; charset=UTF-8")
public UserDto testXmlRequest(@RequestBody UserDto dto){
dto.chgName("2342424sdfsdfsdf");
return dto;
}
produces 設置響應的數據格式。最終httpMessageConverter根據produces的響應media-type來選擇對應的轉換類。
實體類
@XmlRootElement(name = "xml") public class UserDto { @XmlElement(name = "id") private Integer id; @XmlElement(name = "name") private String name; @XmlElement(name = "sex") private Integer sex; public UserDto() { } public UserDto(Integer id, String name, Integer sex) { this.id = id; this.name = name; this.sex = sex; } public void chgName(String name){ this.name = name; } }
javax.xml.bind.annotation.*的相關註解。會自動封裝和解析。註意:對應的field不能有getter和setter,不然會報錯。
因此,通常對於屬性的設置,創建對應的builder類就可以了。
例子
headers:Content-Type=application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <xml> <id>12131</id> <name>test</name> <sex>1</sex> </xml>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
<id>12131</id>
<name>2342424sdfsdfsdf</name>
<sex>1</sex>
</xml>
springMVC xml與實體對象的互轉