0

我想在 REST 控制器类(方法)上添加 JSON 消息。例如我有删除方法看起来像:

@DeleteMapping("/people/{id}")
    public ResponseEntity<PersonDto> deletePerson(@PathVariable Long id) {
        return personService
                .deletePerson(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

我想返回已删除的消息人(可能是 id 数)。我应该使用 ExceptionHandler 吗?或者我可以使用 exceptionHnadler 来做到这一点吗?

4

1 回答 1

0

ResponseBean将POJO 类定义为

public class ResponseBean {

    public final Long id;
    public final String msg;

    public ResponseBean(Long id, String msg) {
        this.id = id;
        this.msg = msg;
    }

    public Long getId() {
        return id;
    }

    public String getMsg() {
        return msg;
    }
}

将您的控制器方法更改为

@DeleteMapping("/people/{id}")
public ResponseEntity<ResponseBean> deletePerson(@PathVariable Long id) {
    return personService
            .deletePerson(id)
            .map(dto -> new ResponseBean(dto.getId(), "Person Deleted Successfully"))
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}

回复

{
  "id" : 2,
  "msg" : "Person Deleted Successfully"
}

您可以根据ResponseBean需要自定义课程。

于 2018-05-10T08:54:20.170 回答