我正在学习 Spring Core 认证,我对 Spring MVC 中的**RESTful webapp* 练习有一些疑问。
因此,在示例中,我使用以下方法创建新的 Account 对象
/**
* Creates a new Account, setting its URL as the Location header on the
* response.
*/
@RequestMapping(value = "/accounts", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public HttpEntity<String> createAccount(@RequestBody Account newAccount,
@Value("#{request.requestURL}") StringBuffer url) {
Account account = accountManager.save(newAccount);
return entityWithLocation(url, account.getEntityId());
}
我知道:
@RequestMapping 注释,在这种情况下,指定此方法处理对 /accounts 资源的 POST HttpRequest。我知道它使用 POST 请求,因为根据 REST 样式,POST“动词”意味着必须创建新资源。
我认为这个注解:
@ResponseStatus(HttpStatus.CREATED)
表示当方法正确结束时(当 HttpResponse 被发送到客户端时)它会将 201 (CREATED) 放入HttpResponse 状态字段。所以它指定新对象的创建已经成功。这是真的还是我遗漏了什么?
方法的第一个参数是:
@RequestBody Account newAccount
在我看来,阅读文档时,此参数绑定(bind)到 Web 请求的主体。请求的主体通过 HttpMessageConverter 传递,以根据请求的内容类型解析方法参数。
那么,究竟是什么意思呢?我认为这意味着在我的 HttpRequest 的 body 中,我有我的 JSON 格式的 Account 对象,并且使用 Jackson 将其转换为经典的 Account Java 对象。是正确的还是我遗漏了什么?
该方法的第二个参数是:
@Value("#{request.requestURL}") StringBuffer url
具体是什么意思?
然后该方法将获得的对象保存到数据库中。
最后它返回:
return entityWithLocation(url, account.getEntityId());
但究竟是什么意思呢?什么回来了?在哪里?结果是不是进入了HttpResponse?
编辑 1:
entityWithLocation() 方法在上一个方法的同一个类中定义,这是它的代码:
private HttpEntity<String> entityWithLocation(StringBuffer url,
Object resourceId) {
// Configure and return an HttpEntity object - it will be used to build
// the HttpServletResponse
HttpHeaders headers = new HttpHeaders();
headers.setLocation(getLocationForChildResource(url, resourceId));
return new HttpEntity<String>(headers);
}
最佳答案
以下是我对你问题的理解。
@RequestBody Account newAccount
关于这一点,你的理解是正确的。
- @Value("#{request.requestURL}") StringBuffer url
相当于request.getRequestURL();参见 API
- entityWithLocation(url, account.getEntityId())
根据此方法中的代码。
它返回 HttpEntity
对象,它代表 http 请求或响应实体(包括 header 和正文
),在您的情况下它是 response
。
在该方法中,您添加了创建的 resource(account)
的 location
。
关于java - 这个在 Spring 中处理 POST 请求的 REST 方法到底是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650149/