dimanche 22 février 2015

How exactrly works this REST method that create a new object?

I am studying for the Spring Core certification and I have the following doubt related how Spring MVC handle a controller method of a example Spring MVC webapp.


So, in my example, I have this method:



/**
* 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 this method create a new account into the DB.


So it handle POST Http Request (representing an insertion operation) toward the URL /accounts.


The createAccount() method take 2 parameters:




  1. @RequestBody Account newAccount: I think that it extract the Account object from the body field of the request. It should be in JSON format and then it is automatically converted into a standard Java object (instance of Account class in this case).




  2. @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?




Then the method simply use a DAO class to persist the object on the DB and finally it return an HttpEntity object as result.


This HttpEntity is created by the entityWithLocation() method definied in the same class, this one:



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);
}


From what I have understand reading the Spring official documentation in this case this object represents the HttpResponse entity that consist of consisting of headers and body.


My doubts are about this oject are:




  1. In my case it is setted only the heder with the url value (the URL used by the client to make the request) and with the id of the new inserted object. The body field of this HttpResponse is empty?




  2. Why have I to return this HttpResponse object? For what is used?




Tnx


Aucun commentaire:

Enregistrer un commentaire