REST - 返回创建的对象与Spring MVC(REST - Returning Create

2019-08-31 16:30发布

I have a REST call that accepts a JSON object, lets say, a person. After I create this object (validated and saved to the database), I need to return the newly created JSON Object.

I think the standard practice is to return 201 Accepted instead of returning the object immediately. But my application needs the newly created object immediately.

I have a controller methods that takes a POST call, calls a service class, which in turn calls a DAO that uses Hibernate to create the object. Once it's saved to the database, I am calling another controller method that takes the ID of the person and returns the Object.

My question, is this the better approach? That is calling another Controller method to get the newly created object. Or the POST call itself should return the Object.

The main question is: Calling another method takes a round trip and I guess it's an overkill. (Service->DAO->Hibernate->Database). Instead I think I should get the Object from the database immediately after it's saved in the same call (from the method that handled POST).

What is the architecture standard here?

Answer 1:

尝试使用ResponseEntity与您需要的对象一起返回的HTTP状态。

示例代码(这是我的代码,我是回客户对象,将其更改为按您的需要):

// imports (for your reference)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

// spring controller method
@RequestMapping(value = "getcust/{custid}", method = RequestMethod.GET, produces={"application/json"})
public ResponseEntity<Customer> getToken(@PathVariable("custid") final String custid, HttpServletRequest request) {

    customer = service.getCustById(custid);

    return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}

阅读本文档了解更多。 一些示例代码已经提供在那里。



Answer 2:

从对POST HTTP规范 :

如果资源已经被原始服务器上创建,响应应该是201(创建)和包含其描述了请求的状态,指的是新的资源的实体,和一个Location头部(见14.30)。

你将在响应身体恢复将取决于如何严格您解释an entity which describes the status of the request and refers to the new resource -和许多实现简单地返回新创建的实体本身的表示。 最重要的是设置Location头中的响应是新创建的资源的URI,使客户可以立即提取它,如果他们选择这样做。



Answer 3:

你可以只用@ResponseBody,@ResponseStatus后坚持之后返回实体对象,但它不是标准的,所以你的客户必须要知道这个定制的,否则,如果您的客户端依赖于标准的API,你必须卡住的标准通过返回无效。



文章来源: REST - Returning Created Object with Spring MVC