本文共 1226 字,大约阅读时间需要 4 分钟。
继上一章的生成JSON示例,现在还有另一种选择,就是使用@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示例:
参考:
==>如有问题,请联系我:easonjim#163.com,或者下方发表评论。<==转载地址:http://xrhal.baihongyu.com/