简体   繁体   English

如何更改响应状态代码以在Swagger中成功运行?

[英]How to change the response status code for successful operation in Swagger?

As shown in the image, it says "Response Class (Status 200)" for the add operation. 如图中所示,添加操作显示为“ Response Class(Status 200)”。 However, the add operation has been implemented in such a way that it will never return 200. It returns 201 on success. 但是,添加操作已实现为永远不会返回200。成功返回201。

My question is how can I change the (Status 200) to (Status 201)? 我的问题是如何将(状态200)更改为(状态201)? The code for this part is as follows: 该部分的代码如下:

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

Thanks! 谢谢!

在此处输入图片说明

You can add the @ResponseStatus annotation to any a controller method to define the http status it should return. 您可以将@ResponseStatus批注添加到任何控制器方法中,以定义应返回的http状态。 Ex 防爆

Adding the following annotation on acontroller method: 在acontroller方法上添加以下注释:

@ResponseStatus(code = HttpStatus.CREATED)

Will return a HTTP status 201 (Created) 将返回HTTP状态201(已创建)

在控制器方法(方法= requestMethod.PUT)或(方法= requestMethod.POST)@ResponseStatus(代码= HttpStatus.ACCEPTED)中添加以下注释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Springfox Swagger中删除操作的响应体? - How to remove the response body of an operation in Springfox Swagger? 使用 Spring WebClient 访问成功请求的响应状态码 - Access response status code for successful requests using Spring WebClient 如何更改 Spring Boot 错误响应中的状态代码? - How to change Status code in spring boot error response? 使用@ControllerAdvice和@ResponseStatus更改响应状态代码 - Change Response status code using @ControllerAdvice and @ResponseStatus Swagger 3 / OpenApi 如何为同一个状态码添加两个描述 - Swagger 3 / OpenApi How to add two descriptions to the same status code 成功登录后发送自定义对象作为响应以及状态码200,而无需内部重定向 - Send custom object as response along with status code 200 on successful login without internal redirection Spring Security:如何更改响应的 HTTP 状态? - Spring Security: how to change HTTP Status for response? Swagger - 渲染声明异常的响应状态 - Swagger - Render response status for declared exception 如何设置HTTP响应的服务器状态代码? - how to set the server status code for http response? 更改响应状态 onUnsuccessfulAuthentication - Change response status onUnsuccessfulAuthentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM