如何将http状态添加到所有响应dto(数据传输对象)?

时间:2016-05-17 22:07:55

标签: spring spring-boot swagger dto

我一直在开发Spring Boot REST API。到目前为止,除了我的问题,我做了很多事情。我使用springfox swagger UI进行文档编制,我将模型和dtos分开以获得更好的结构。

我有一个基础dto模型:

public class BaseDto {

 private int code;
 private boolean success;

 public BaseDto() {
    this.code = HttpStatus.OK.value();
    this.success = HttpStatus.OK.is2xxSuccessful();
 }

}

当然,我通过扩展它来使用这个类:

@ApiModel("User")
public class UserDto extends BaseDto {
    private String email;
    private String username;
    // stuffs
}

如果我在使用此结构时执行用户请求,我会得到:

{
  code: 200,
  success: true,
  email: "",
  username: ""
}

等等......那很好,但在其他dtos中,比如帖子模型,我有UserDto列表,并以它的形式显示。在每个对象中,"代码"和"成功"字段写;但是,这不是我想要的。

我想实现的目标只有一次"代码"和"成功"写在响应JSON主体中而不是所有返回列表对象。

为了澄清更多这是Post Dto Model并返回如下:

{
  "code": 0,
  "createdAt": "2016-05-17T21:59:37.512Z",
  "id": "string",
  "likes": [
    {
      "code": 0,
      "createdAt": "2016-05-17T21:59:37.512Z",
      "deviceType": "string",
      "email": "string",
      "fbAccessToken": "string",
      "fbId": "string",
      "followers": [
        {}
      ],
      "followings": [
        {}
      ],
      "id": "string",
      "profileImage": "string",
      "success": true,
      "token": "string",
      "udid": "string",
      "updatedAt": "2016-05-17T21:59:37.512Z",
      "username": "string",
      "version": 0
    }
  ],
  "pictures": [
    "string"
  ],
  "postedBy": {
    "code": 0,
    "createdAt": "2016-05-17T21:59:37.512Z",
    "deviceType": "string",
    "email": "string",
    "fbAccessToken": "string",
    "fbId": "string",
    "followers": [
      {}
    ],
    "followings": [
      {}
    ],
    "id": "string",
    "profileImage": "string",
    "success": true,
    "token": "string",
    "udid": "string",
    "updatedAt": "2016-05-17T21:59:37.512Z",
    "username": "string",
    "version": 0
  },
  "success": true,
  "text": "string",
  "updatedAt": "2016-05-17T21:59:37.512Z",
  "userId": "string",
  "userIds": [
    "string"
  ],
  "version": 0
}

您可以在Post Dto模型中看到使用User Dto的地方,代码和成功字段被添加为冗余。

我不太了解我的错误做法。也许,我应该使用向所有返回的DTO添加全局HTTP状态响应。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您可以创建响应并设置HttpStatus,则可以拥有AppUtil类。在AppUtil类中编写如下方法:

public static ResponseEntity<ResponseEnvelope> successResponse(Object data,
        int messageCode, String message) {
    ResponseEnvelope envelope = new ResponseEnvelope(data, true, message,
            messageCode);
    ResponseEntity<ResponseEnvelope> responseEntity = new ResponseEntity<>(
            envelope, HttpStatus.OK);
    return responseEntity;
}

successResponse方法中,您可以设置data中的ResponseEnvelope对象,其中HttpStatus将与ResponseEntity一起发送到您想要的UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(100, 200, 100, 100)]; [label setFont:[UIFont fontWithName:@"Icons8" size:100]]; [label setText:[NSString stringWithUTF8String:"&#xf100;"]]; [self.view addSubview:label]; 回来。

查看我之前的回答here