Kev*_*ave 5 java rest standards json spring-mvc
我有一个REST调用接受一个JSON对象,比方说,一个人.在我创建此对象(验证并保存到数据库)后,我需要返回新创建的JSON对象.
我认为标准做法是返回201 Accepted而不是立即返回对象.但我的应用程序需要立即新创建的对象.
我有一个控制器方法,它接受一个POST调用,调用一个服务类,然后调用一个使用Hibernate来创建对象的DAO.一旦它保存到数据库,我正在调用另一个控制器方法,该方法获取人员的ID并返回对象.
我的问题是,这是更好的方法吗?这是调用另一个Controller方法来获取新创建的对象.或者POST调用本身应该返回Object.
主要问题是: 调用另一种方法需要往返,我猜这是一种矫枉过正.(服务- > DAO-> Hibernate->数据库).相反,我认为我应该在相同的调用(从处理POST的方法)中保存后立即从数据库中获取对象.
这里的架构标准是什么?
Jee*_*til 19
尝试使用ResponseEntity它返回HTTP状态以及您需要的对象.
示例代码是(这是我的代码,我将返回Customer对象,根据您的需要进行更改):
// 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);
}
Run Code Online (Sandbox Code Playgroud)
阅读此文档以了解更多信息.那里提供了一些示例代码.
| 归档时间: |
|
| 查看次数: |
17171 次 |
| 最近记录: |