[英]How to add http status to all responses dto(data transfer object)?
我一直在開發Spring Boot REST API。 到目前為止,除了我的問題,我已經做了很多事情。 我正在使用springfox swagger UI進行文檔編制,並且我將模型和dto分開以獲得更好的結構。
我有一個基本的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: ""
}
依此類推...很好,但是在其他dto中,例如后期模型,我有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
}
您可以在使用用戶Dto的Post Dto模型中看到,冗余添加了代碼和成功字段。
我不大可能知道我弄錯了方法。 也許,我應該使用向所有返回的DTO添加全局HTTP狀態響應的方法。
有人可以幫忙嗎?
您可以創建一個AppUtil類,然后創建響應並設置HttpStatus
。 在您的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
方法中,您可以在ResponseEnvelope
設置data
對象,該對象與HttpStatus
將在您要返回的ResponseEntity
中發送。
在這里查看我以前的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.