带有元数据的Response.ok

时间:2018-07-23 09:43:44

标签: java spring restful-architecture

在我的RESTful服务项目中,我有添加记录(新人员)的方法:

在控制器中:

@PostMapping(value = "/addPerson")
public Response dodajOsobe(InputStream inputStream) {
    return osMgr.dodajOsobe(inputStream);
}

服务中:

public Response dodajOsobe(InputStream inputStream) {

    Response response = null;
    try {
        String input = misc.InputStreamToString(inputStream);
        Integer id = dodajOsobe(input);
        response = Response.ok("New person added").build();
    } catch (Exception e) {
        response = Response.serverError().entity("Nie udało się dodać osoby. Przyczyna: " + e.getLocalizedMessage()).build();
    }
    return response;
}

如果一切正常,它将返回状态为“ OK”的对象“ Response”:

response = Response.ok("New person added").build();

在浏览器中执行结果后,如下所示:

{
    "statusType": "OK",
    "entity": "New person added",
    "entityType": "java.lang.String",
    "metadata": {},
    "status": 200
}

我想返回该人的身份证。我知道我可以在“实体”中执行此操作,但是我想在此获取可重复的信息。 有字段“元数据”,我不会在这里放置记录的ID,像这样:

{
    "statusType": "OK",
    "entity": "New person added",
    "entityType": "java.lang.String",
    "metadata": {"id":112233},
    "status": 200
}

该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以创建自定义响应类,例如

class OkResponse {
  private EntityId id; //or something else
  private String message;
}

并返回其实例作为响应。

答案 1 :(得分:0)

我终于添加了标头方法:

        response = Response.ok("New record added")
                .header("rezerwacjaId", rezId)
                .build();

并获得了JSON:

{
  "entity": "New record added",
  "entityType": "java.lang.String",
  "metadata": {
    "rezerwacjaId": [
      77754
    ]
  },
  "status": 200,
  "statusType": "OK"
}