xml练习,得到的结果是:
200
success 李四 2
需要用的的注解:@ResponseBody
org.springframework.web.bind.annotation.ResponseBody;
将内容输出为xml,json格式(非html格式)
其他注解:
javax.xml.bind.annotation.XmlElement;
javax.xml.bind.annotation.XmlElements;javax.xml.bind.annotation.XmlRootElement;javax.xml.bind.annotation.XmlAccessorType;javax.xml.bind.annotation.XmlAccessType;
包名:json
user.java
package json;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;@XmlRootElement@XmlAccessorType(XmlAccessType.NONE)public class User { @XmlElement String name; @XmlElement Integer id; public User(String name, Integer id) { this.name = name; this.id = id; } public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
BaseXmlResult.java根信息
package json;public class BaseXmlResult { protected String code; protected String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
UserActiveResult.java User列表信息
package json;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlElements;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;@XmlRootElement(name="xml")@XmlAccessorType(XmlAccessType.NONE)public class UserActiveResultextends BaseXmlResult { @XmlElements({ @XmlElement(name="user", type=User.class) }) private T data; public T getData() { return data; } public void setData(T data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
再来看看UserController.java
package json;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping(value="/user")public class UserController { @RequestMapping(value="/list", method=RequestMethod.GET) @ResponseBody public UserActiveResult getUser() { UserActiveResultlist = new UserActiveResult (); list.setCode("200"); list.setMessage("success"); User user = new User(); user.setId(1); user.setName("张三"); list.setData(user); return list; }}