如何更改Swagger中成功操作的响应状态代码

如何更改Swagger中成功操作的响应状态代码

本文介绍了如何更改Swagger中成功操作的响应状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如图所示,它为添加操作显示响应类(状态200)。但是,添加操作的实现方式是永远不会返回200.成功后返回201.

As shown in the image, it says "Response Class (Status 200)" for the add operation. 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)?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);
    }
}

谢谢!

推荐答案

您可以添加 @ResponseStatus 对任何控制器方法的注释,以定义它应返回的http状态。 Ex

You can add the @ResponseStatus annotation to any a controller method to define the http status it should return. Ex

在acontroller方法上添加以下注释:

Adding the following annotation on acontroller method:

@ResponseStatus(code = HttpStatus.CREATED)

将返回HTTP状态201(已创建)

Will return a HTTP status 201 (Created)

这篇关于如何更改Swagger中成功操作的响应状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:21