如何在 Swagger 中更改成功操作的响应状态代码?
How to change the response status code for successful operation in Swagger?
如图所示,它表示 "Response Class (Status 200)" 用于添加操作。但是,添加操作的实现方式永远不会 return 200。成功时 returns 201。
我的问题是如何将 (Status 200) 更改为 (Status 201)?
这部分的代码如下:
@RequestMapping(method = RequestMethod.PUT, value = "/add")
@ApiOperation(value = "Creates a new person", code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Record created successfully"),
@ApiResponse(code = 409, message = "ID already taken")
})
public ResponseEntity<String> add(@RequestParam(value = "name", required = true) String name,
@RequestParam(value = "id", required = true) String id) {
if (PD.searchByID(id).size() == 0) {
Person p = new Person(name, id);
PD.addPerson(p);
System.out.println("Person added.");
return new ResponseEntity<String>(HttpStatus.CREATED);
} else {
System.out.println("ID already taken.");
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
谢谢!
您可以将 @ResponseStatus
注释添加到任何控制器方法以定义它应该 return 的 http 状态。例如
在控制器方法上添加以下注释:
@ResponseStatus(code = HttpStatus.CREATED)
将 return HTTP 状态 201(已创建)
在控制器方法(method = requestMethod.PUT)或(method = requestMethod.POST)中添加以下注解
@ResponseStatus(代码=HttpStatus.ACCEPTED)
如图所示,它表示 "Response Class (Status 200)" 用于添加操作。但是,添加操作的实现方式永远不会 return 200。成功时 returns 201。
我的问题是如何将 (Status 200) 更改为 (Status 201)? 这部分的代码如下:
@RequestMapping(method = RequestMethod.PUT, value = "/add")
@ApiOperation(value = "Creates a new person", code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Record created successfully"),
@ApiResponse(code = 409, message = "ID already taken")
})
public ResponseEntity<String> add(@RequestParam(value = "name", required = true) String name,
@RequestParam(value = "id", required = true) String id) {
if (PD.searchByID(id).size() == 0) {
Person p = new Person(name, id);
PD.addPerson(p);
System.out.println("Person added.");
return new ResponseEntity<String>(HttpStatus.CREATED);
} else {
System.out.println("ID already taken.");
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
谢谢!
您可以将 @ResponseStatus
注释添加到任何控制器方法以定义它应该 return 的 http 状态。例如
在控制器方法上添加以下注释:
@ResponseStatus(code = HttpStatus.CREATED)
将 return HTTP 状态 201(已创建)
在控制器方法(method = requestMethod.PUT)或(method = requestMethod.POST)中添加以下注解 @ResponseStatus(代码=HttpStatus.ACCEPTED)