继上一章的生成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