I am studying for the Spring Core certification and I have some doubt related to an exercise on **RESTful webapp* in Spring MVC.
So, in the example, I have the following method that create a new 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());
}
I know that:
@RequestMapping annotation, in this case, specify that this method handle POST HttpRequest towards the /accounts resource. I know that it use the POST request because according to the REST style the POST "verbs" means that a new resource have to be created.
I think that this annotation:
@ResponseStatus(HttpStatus.CREATED)
means that when the method correctly end (when the HttpResponse is send to the client) it put the 201 (CREATED) into the HttpResponse status field. So it specify that the creation of the new object is gone ok. Is it true or am I missing something?
The first parameter of the method is:
@RequestBody Account newAccount
Reading the documentation it seems to me that this parameter is bounded to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request.
So, what exactly means? I think that it means that into the body of my HttpRequest I have my Account object in JSON format and that it is used Jackson to convert it into a classic Account Java object. Is it right or am I missing something?
The second parameter of the method is:
@Value("#{request.requestURL}") StringBuffer url
What exactly means?
Then the method save the obtained object on the database.
Finally it return:
return entityWithLocation(url, account.getEntityId());
but what exactly means? what is returning? and where? the result is not into the HttpResponse?
EDIT 1:
The entityWithLocation() method is definied in the same class of the previous method and this is its code:
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);
}
Below is my understanding on your question.
Your understanding is correct,regarding this point.
It is equivalent to request.getRequestURL(); See API
As per code inside this method. It returns
HttpEntity
Object,which represent http request or response entity(which includes headers and body
),in your case it isresponse
. Inside the method,you have added thelocation
ofresource(account)
created.