【发布时间】:2015-04-23 09:09:28
【问题描述】:
我正在学习 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 注释,在这种情况下,指定此方法处理 POST 对 /accounts 资源的 HttpRequest。我知道它使用 POST 请求,因为根据 REST 样式,POST“动词”意味着必须创建一个新资源。
-
我认为这个注释:
@ResponseStatus(HttpStatus.CREATED)表示当方法正确结束时(当 HttpResponse 发送到客户端时)它会将 201 (CREATED) 放入HttpResponse 状态字段。因此它指定新对象的创建已经正常。这是真的还是我错过了什么?
-
方法的第一个参数是:
@RequestBody Account newAccount阅读文档在我看来,此参数绑定到 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);
}
【问题讨论】:
-
entityWithLocation 方法定义在哪里?你能发布它的实现吗?
-
@TyrionLannister 编辑了我的原始帖子,添加了所需的信息
标签: java spring rest spring-mvc annotations