1. 程式人生 > 實用技巧 >Restful API返回統一響應體 :restful api介面,返回統一響應體

Restful API返回統一響應體 :restful api介面,返回統一響應體

先建一個工具類如

RestResponse.java
package com.ibaiqi.news.sqgov.tool;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;
import java.util.Date;

/**
 *
 * @author [email protected]
 * @date 2018/9/26
 * REST請求響應工具類 ,在controller控制器中,做為介面返回值  return RestResponse.buildSuccess(articles);
 */
public class RestResponse implements Serializable {

    private final static long serialVersionUID = 1L;
    /**
     * 成功
     */
    private final static int STATUS_SUCCESS = 200;

    /**
     * 程式碼錯誤
     */
    private final static int STATUS_ERROR_INTERNAL_SERVER_ERROR = 500;

    /**
     * 服務不可用(針對熔斷&服務降級的情況)
     */
    private final static int STATUS_ERROR_SERVICE_UNAVAILIABLE = 503;


    private int status;
    //@JsonInclude(JsonInclude.Include.NON_NULL)//不為空時,返回
    private Object data;
    private String message;

    /**
     * 時間戳並格式化
     */
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "lz",timezone = "GMT+8")
    private Date timestamp;

    /**
     * 程式耗時
     */
    //@JsonIgnore//不返回註解
    private long time;

    public RestResponse(int code, String message, Object data) {
        super();
        this.status = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 請求成功
     * @param data
     * @return
     */
    public static RestResponse buildSuccess(Object data) {
        return new RestResponse(STATUS_SUCCESS, "success", data);
    }


    /**
     * 程式碼錯誤
     * @param data
     * @return
     */
    public static RestResponse buildError_InternalServerError(Object data) {
        return new RestResponse(STATUS_ERROR_INTERNAL_SERVER_ERROR, "error", data);
    }

    /**
     * 返回錯誤碼(服務不可用時,返回此方法),但推薦直接使用異常類
     * @param data
     * @return
     */
    public static RestResponse buildError_ServiceUnavailable(Object data) {
        return new RestResponse(STATUS_ERROR_SERVICE_UNAVAILIABLE, "error", data);
    }

//    public static RestResponse buildError(Object data) {
//        return new RestResponse(STATUS_SUCCESS, "success", data);
//    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getTimestamp() {
        return new Date();
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getTime() {
        return time + "ms";
    }

    public void setTime(long time) {
        this.time = time;
    }

}

2:控制器類controller 類中方法引用

@RestController
@RequestMapping("/api")
@Api("政務要聞文章Controller介面")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ArticlesController {
    @Resource
    ArticlesService articlesService;

    
    /**
     * 列出Articles且帶上分頁資訊
     *
     * @return
     */
    @GetMapping("/V1/articlesResResult/{pageSize}")
    @ResponseBody
    @ApiOperation(value = "列出文章,且帶分頁資訊", notes = "返回Articles物件的集合")
    public RestResponse articlesResResult(
            @ApiParam(name = "pageSize", value = "輸入每頁顯示頁數", defaultValue = "3", required = true) @PathVariable Integer pageSize
    ) {
//        Map<String, Object> map = new HashMap<>();
        PageInfo<Articles> articles = articlesService.listArticles(1, pageSize);
//        map.put("data",articles);
//        map.put("msg","查詢所有使用者及分頁資訊成功");
        //        return  RestResponse.buildSuccess(map);
        return RestResponse.buildSuccess(articles);

    }
}