我有一个方法用以下方式注释:
/**
* 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>
之前对象,所以我认为它指的是这个列表。类(class)文档指出,此注释的作用是:
ensure that the result will be written to the HTTP response by an HTTP Message Converter (instead of an MVC View).
同时阅读官方 Spring 文档:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
似乎需要List<Account>
对象并将其放入 Http Response
.这是正确的还是我误解了?
写在前面accountSummary()
的评论里方法有:
You should get JSON results when accessing http://localhost:8080/rest-ws/app/accounts
那么这到底是什么意思?这是否意味着 List<Account>
accountSummary()
返回的对象方法自动转换为 JSON
格式然后放入Http Response
?还是什么?
如果这个断言为真,在哪里指定对象会自动转换成JSON
格式? @ResponseBody
是采用的标准格式吗?使用了注解还是在其他地方指定了注解?
最佳答案
首先,注解不注解List
。它注释方法,就像 RequestMapping
一样。你的代码相当于
@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
return accountManager.getAllAccounts();
}
现在注解的意思是方法的返回值将构成HTTP响应的主体。当然,HTTP 响应不能包含 Java 对象。因此,此帐户列表将转换为适合 REST 应用程序的格式,通常是 JSON 或 XML。
格式的选择取决于安装的消息转换器,produces
attribute 的值。 @RequestMapping
注释,以及客户端接受的内容类型(在 HTTP 请求 header 中可用)。例如,如果请求说它接受 XML,但不接受 JSON,并且安装了可以将列表转换为 XML 的消息转换器,则将返回 XML。
关于java - Spring @ResponseBody 注释是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646332/