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

时间:2016-05-24 05:41:21

标签: java spring-mvc swagger-ui swagger-2.0 springfox

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

我的问题是如何将(状态200)更改为(状态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);
    }
}

谢谢!

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以将@ResponseStatus批注添加到任何控制器方法中,以定义应返回的http状态。例如

在控制器方法上添加以下注释:

@ResponseStatus(code = HttpStatus.CREATED)

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

答案 1 :(得分:-1)

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