繼上一章的生成JSON示例http://www.cnblogs.com/EasonJim/p/7500405.html,現在還有另一種選擇,就是使用@RestController,下面將參照上一節例子進行改造,展示核心代碼。
UserController.java
package com.jsoft.testspringmvc.controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.jsoft.testspringmvc.model.User; @RestController @RequestMapping("/user") public class UserController { @RequestMapping(value = "{name}", method = RequestMethod.GET) public User getUser(@PathVariable String name) { User user = new User(); user.setName(name); user.setId(1); return user; } }
結果:
如果想要返回XML數據,直接在實體里面標記@XmlRootElement即可,比如下面所示的POJO類
package com.jsoft.testspringmvc.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") public class User { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
Maven示例:
https://github.com/easonjim/5_java_example/tree/master/springmvc/tutorialspoint/test33
參考:
http://www.yiibai.com/spring_mvc/spring-4-mvc-rest-service-example-using-restcontroller.html