【发布时间】:2015-04-23 03:45:01
【问题描述】:
我有一个方法用以下方式注释:
/**
* Provide a list of all accounts.
*/
// TODO 02: Complete this method. Add annotations to respond
// to GET /accounts and return a List<Account> to be converted.
// Save your work and restart the server. You should get JSON results when accessing
// http://localhost:8080/rest-ws/app/accounts
@RequestMapping(value="/orders", method=RequestMethod.GET)
public @ResponseBody List<Account> accountSummary() {
return accountManager.getAllAccounts();
}
所以我通过这个注释知道:
@RequestMapping(value="/orders", method=RequestMethod.GET)
此方法处理对由 URL /orders 表示的资源发出的 GET HTTP 请求。
此方法调用返回 List 的 DAO 对象。
其中 Account 代表系统上的一个用户,并且有一些代表该用户的字段,例如:
public class Account {
@Id
@Column(name = "ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long entityId;
@Column(name = "NUMBER")
private String number;
@Column(name = "NAME")
private String name;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "ACCOUNT_ID")
private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();
...............................
...............................
...............................
}
我的问题是:@ResponseBody 注释究竟是如何工作的?
它位于返回的List<Account> 对象之前,所以我认为它指的是这个列表。课程文档指出,此注释的作用是:
确保结果将通过 HTTP 写入 HTTP 响应 消息转换器(而不是 MVC 视图)。
同时阅读官方 Spring 文档:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
它似乎将List<Account> 对象放入Http Response。这是正确的还是我误解了?
写入前面accountSummary()方法的注释里面有:
访问时应该会得到 JSON 结果 http://localhost:8080/rest-ws/app/accounts
那么这到底是什么意思?是不是说accountSummary()方法返回的List<Account>对象自动转换成JSON格式再放入Http Response?还是什么?
如果这个断言为真,在哪里指定对象会自动转换成JSON格式?使用@ResponseBody注解时是采用标准格式还是在别处指定?
【问题讨论】:
标签: java json spring rest spring-mvc