我正在学习 Spring Core 认证,我对 Spring MVC 中 **RESTful webapp* 的练习有一些疑问。
因此,在示例中,我使用以下方法创建一个新的Account object
/**
* 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注解,在本例中,指定该方法句柄POSTHttpRequest 朝向/账户资源。我知道它使用POST请求,因为根据 REST 风格,POST“动词”意味着必须创建新资源。
-
我认为这个注释:
@ResponseStatus(HttpStatus.CREATED)
意味着当方法正确结束时(当Http响应发送给客户端)它把201 (CREATED) 到 HttpResponse 状态字段中。所以它表明新对象的创建已经成功。这是真的还是我错过了什么?
-
该方法的第一个参数是:
@RequestBody Account newAccount
阅读文档后,我发现该参数与 Web 请求的正文相关。请求正文通过 HttpMessageConverter 传递,以根据请求的内容类型解析方法参数。
那么,到底是什么意思呢?我认为这意味着进入body我的 HttpRequest 我有 JSON 格式的 Account 对象,并且使用 Jackson 将其转换为经典AccountJava 对象。这是正确的还是我错过了什么?
-
该方法的第二个参数是:
@Value("#{request.requestURL}") StringBuffer url
到底是什么意思?
然后该方法将获得的对象保存到数据库中。
-
最后返回:
return entityWithLocation(url, account.getEntityId());
但到底是什么意思呢?什么正在返回?哪里?结果没有进入HttpResponse?
EDIT 1:
The 实体与位置()方法与前一个方法在同一个类中定义,这是它的代码:
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 http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRequestURL()
- entityWithLocation(url, account.getEntityId())
根据该方法内的代码。
它返回HttpEntity
对象,代表http请求或响应实体(which includes headers and body
),在你的情况下是response
。
在方法内部,您添加了location
of resource(account)
创建的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)