我正在学习 Spring Core 认证,对于 Spring MVC 如何处理示例 Spring MVC web 应用程序的 Controller 方法有以下疑问。
所以,在我的示例中,我有这个方法:
/**
* 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());
}
我知道此方法会在数据库中创建一个新帐户。
因此它会处理针对 URL /accounts 的 POST Http 请求(表示插入操作)。
createAccount() 方法有 2 个参数:
@RequestBody Account newAccount:我认为它从请求的正文字段中提取 Account 对象。它应该是 JSON 格式,然后自动转换为标准 Java 对象(在本例中为 Account 类的实例)。
@Value("#{request.requestURL}") StringBuffer url:我认为这与做类似的事情是一样的:
request.getRequestURL();
并且它包含客户端用于发出请求的 URL。这是真的吗?但为什么它将它放入 StringBuffer 中而不是放入简单的 String 中?
然后该方法只需使用 DAO 类将对象持久保存在数据库上,最后返回一个 HttpEntity 对象作为结果。
这个HttpEntity是由同一个类中定义的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);
}
根据我阅读 Spring 官方文档的理解,在这种情况下,该对象表示 HttpResponse 实体,它由 header 和正文组成。
我对这个项目的疑问是:
在我的例子中,它仅设置具有 url 值(客户端用于发出请求的 URL)和新插入对象的 id 的 heder。此 HttpResponse 的正文字段为空?
为什么我要返回这个 HttpResponse 对象?有什么用?
Tnx
最佳答案
@Value("#{request.requestURL}") StringBuffer url: I think that it is the same thing of do somtthing like to:
request.getRequestURL();
And it contains the URL used by the client to make the request. Is it true? But why it put it into a StringBuffer and not into a simple String?
因为方法HttpServletRequest.getRequestURL()
返回 StringBuffer,而不是 String。
The body field of this HttpResponse is empty?
是的,是的,因为代码没有填充它。您可以简单地使用浏览器调用此操作并查看返回的响应。
Why have I to return this HttpResponse object? For what is used?
您不必。但您可以选择。那取决于你。您应该知道为什么要返回。程序员的目的是返回一个没有正文的 HTTP 响应,其 Location header 包含 URL 和 CREATED 状态。这是 REST 应用程序中 POST 之后返回的常规内容:POST 用于创建新资源,它返回 CREATED 状态以表明该资源已正确创建,并返回所创建资源的 URL,以便客户端可以获取该资源并检查其包含的内容。
关于java - 这个创建新对象的 REST 方法到底是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657056/