統一返回對象類

1、常量類(加載狀態碼文件)

package com.common;

import java.io.IOException;
import java.util.Properties;

public class Constant {

    public static Properties prop=new Properties();

    static {
        try {
            prop.load(Constant.class.getClassLoader().getResourceAsStream("loginAndReg.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static final int DEFAULT_SUCCESS = Integer.parseInt(prop.getProperty("DEFAULT_SUCCESS"));
}

2、統一返回對象類:
 

package com.common;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;


@Getter
@Setter
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//序列化json時,時null的對象,key也會消失
public class ServerResponse<T> implements Serializable {
    private Integer status; //狀態碼
    private T data;  //成功時的響應數據(對象)
    private String msg;  //附加信息

    private ServerResponse(Integer status) {
        this.status = status;
    }

    private ServerResponse(Integer status, T data) {
        this.status = status;
        this.data = data;
    }

    private ServerResponse(Integer status, T data, String msg) {
        this.status = status;
        this.data = data;
        this.msg = msg;
    }


    private ServerResponse(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    private ServerResponse(String msg) {
        this.status = 100;
        this.msg = msg;
    }

    /**
     * 成功:默認狀態碼
     * @return
     */
    public static  ServerResponse successRS() {
        return new ServerResponse(Constant.DEFAULT_SUCCESS);
    }

    /**
     * 成功:默認狀態碼+數據
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ServerResponse successRS(T data) {
        return new ServerResponse(Constant.DEFAULT_SUCCESS,data);
    }


    /**
     * 成功:自定義狀態碼,信息
     * @param successCode
     * @param msg
     * @return
     */
    public static ServerResponse successRS(Integer successCode,String msg){
        return new ServerResponse(successCode,msg);
    }

    /**
     * 成功:自定義狀態碼+數據+信息
     * @param successCode
     * @param msg
     * @return
     */
    public static <T>ServerResponse successRS(Integer successCode,T data,String msg){
        return new ServerResponse(successCode,data,msg);
    }


    /**
     * 失敗:狀態碼 + 信息
     * @param errorCode
     * @param errorMessage
     * @return
     */
    public static ServerResponse failedRS(Integer errorCode, String errorMessage) {
        return new ServerResponse(errorCode, errorMessage);
    }



    @JsonIgnore
    //讓success不在json序列化結果之中
    public boolean isSuccess() {
        return this.status == Constant.DEFAULT_SUCCESS;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章