小编典典

Spring @ResponseBody批注如何工作?

json

我有一种通过以下方式注释的方法:

/**
* 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>对象之前,因此我认为它引用了此List。课程文档指出,此注释可用于:

确保结果将通过HTTP消息转换器(而不是MVC视图)写入到HTTP响应中。

还要阅读Spring的官方文档:http :
//docs.spring.io/spring/docs/current/javadoc-
api/org/springframework/web/bind/annotation/ResponseBody.html

似乎它带了List<Account>物体并将它放入了Http Response。这是正确的还是我误会了?

写入前accountSummary()一种方法的注释中有:

访问http:// localhost:8080 / rest-ws / app /
accounts
时,您应该获得JSON结果

那么这到底是什么意思呢?这是否意味着List<Account>accountSummary()方法返回的对象会自动转换为JSON格式,然后放入Http Response?中?或者是什么?

如果此断言为真,则在哪里指定对象将自动转换为JSON格式?@ResponseBody使用注释时是采用标准格式还是在其他地方指定?


阅读 239

收藏
2020-07-27

共1个答案

小编典典

首先,注释不进行注释List。就像方法一样,它对方法进行了注释RequestMapping。您的代码等同于

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

现在注释的意思是方法的返回值将构成HTTP响应的主体。当然,HTTP响应不能包含Java对象。因此,此帐户列表将转换为适合REST应用程序的格式,通常为JSON或XML。

格式的选择取决于已安装的消息转换器,RequestMapping批注的produces属性的值以及客户端接受的内容类型(在HTTP请求标头中可用)。例如,如果请求说它接受XML,但不接受JSON,并且安装了可以将列表转换为XML的消息转换器,则将返回XML。

2020-07-27