[英]How to return CREATED status (201 HTTP) in ResponseEntity
There is a Spring-MVC
application.有一个Spring-MVC
应用程序。 In controllers, when returning the results of methods, I return via ResponseEntity<>
.在控制器中,当返回方法的结果时,我通过ResponseEntity<>
返回。 On success, I return ( 200
statutes) the OK
-method.成功后,我返回( 200
条法规) OK
方法。 But when creating something, I would like to return the CREATED
-method ( 201
status).但是在创建某些东西时,我想返回CREATED
-方法( 201
状态)。 I just can't understand what kind of URL
to ask in parentheses when calling through CREATED
.我只是不明白在通过CREATED
调用时要在括号中询问什么样的URL
。 How can this be implemented?如何实施?
Now I have such an implementation:现在我有这样一个实现:
@PostMapping("/create/dish")
ResponseEntity<Dish> createDish(@Valid @RequestBody DishDTO dishDTO) {
return ResponseEntity.ok(cookService.createDish(dishDTO.getDishName(), dishDTO.getAboutDish(), dishDTO.getDishType(),
dishDTO.getCookingTime(), dishDTO.getWeight(),
dishDTO.getDishCost(), dishDTO.getCooksId()));
}
I want to remake it like this to make it work(now it not work):我想像这样重新制作它以使其工作(现在它不起作用):
@PostMapping("/create/dish")
ResponseEntity<Dish> createDish(@Valid @RequestBody DishDTO dishDTO) {
return ResponseEntity.created(cookService.createDish(dishDTO.getDishName(), dishDTO.getAboutDish(), dishDTO.getDishType(),
dishDTO.getCookingTime(), dishDTO.getWeight(),
dishDTO.getDishCost(), dishDTO.getCooksId()));
}
PS I don't have a frontend at all. PS我根本没有前端。 All through Swagger or PostMan.全部通过 Swagger 或 PostMan。
Just return this way:只需以这种方式返回:
return new ResponseEntity<Dish>(cookService.createDish(...), HttpStatus.CREATED)
Making sure you have imported org.springframework.http.HttpStatus
确保您已导入org.springframework.http.HttpStatus
You can use您可以使用
ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedObjectId).toUri()).build()
If you want to create a 201 (CREATED) response without a body, then use:如果要创建没有正文的 201 (CREATED) 响应,请使用:
ResponseEntity.status(HttpStatus.CREATED).build()
Alternatively to return 201 (Created) status you can also dispose of ResponseEntity and set @ResponseStatus(HttpStatus.CREATED) for RestController method like this或者,要返回 201(已创建)状态,您还可以处理 ResponseEntity 并为 RestController 方法设置 @ResponseStatus(HttpStatus.CREATED) ,如下所示
@PostMapping("/create/dish")
@ResponseStatus(HttpStatus.CREATED)
Dish createDish(@Valid @RequestBody DishDTO dishDTO) {
return cookService.createDish(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.