WebUtils封裝返回值

在項目會有一些請求來規定返回值給前臺,一般封裝個jsonobject對象即可,主要包括:CODE:code,MSG:message,DATA:data三個字段
主要有成功和出錯的兩種情況,這裏我們可以封裝一個ResponseEnum枚舉類專門用於錯誤代碼和錯誤信息提示
如下類

public enum ResponseEnum {
    /**
     * =====================================
     * 0-99
     * =====================================
     */
    SUCCESS("0", "操作成功"),
    FAILURE("1", "操作失敗"),
    INVALID_PARAMS("2", "非法參數"),
    INVALID_SIGN("3", "非法簽名"),
    UNKNOWN_ERROR("4", "未知錯誤"),

   private String code;
   private String message;

    // 構造方法
    private ResponseEnum(String code, String message) {
        this.code = code;
        this.message = message;
    }
    public String getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
}

然後寫一個webutils類來封裝每種返回請求方式

public class WebUtils {

    public static final String CODE = "code";
    public static final String MSG = "message";
    public static final String DATA = "data";

    //成功,無message
    public static JSONObject createSuccResult() {
        return createResp(ResponseEnum.SUCCESS);
    }
    //成功,有message
    public static JSONObject createSuccResult(Object data) {
        JSONObject result = createSuccResult();
        result.put(DATA, data);
        return result;
    }
    //成功,引用某個ResponseEnum類常量來實現
    private static JSONObject createResp(ResponseEnum responseEnum) {
        JSONObject result = new JSONObject();
        result.put(CODE, responseEnum.getCode());
        result.put(MSG, responseEnum.getMessage());
        return result;
    }

    //失敗:沒有message
    public static JSONObject createErrorResult() {
        return createResp(ResponseEnum.UNKNOWN_ERROR);
    }
    //失敗:引用ResponseEnum類常量
    public static JSONObject createErrorResult(ResponseEnum responseEnum) {
        return createResp(responseEnum);
    }
    //失敗,引用某個ResponseEnum類常量,和數據
    public static JSONObject createErrorResult(ResponseEnum responseEnum, Object data) {
        JSONObject resp = createResp(responseEnum);
        resp.put(DATA, data);
        return resp;
    }

    //封裝異常信息
    public static JSONObject createErrorResult(ServiceException e) {
        JSONObject result = new JSONObject();
        result.put(CODE, e.getErrCode());
        result.put(MSG, e.getErrMsg());
        return result;
    }
}

如何調用呢,以後寫接口就不用建立一個jsonobject


    @ResponseBody
    @RequestMapping("/nologin/logout")
    public JSONObject logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            return **WebUtils.createSuccResult()**;

        } catch (Exception e) {
            log.error("", e);
            return WebUtils.createErrorResult(ResponseEnum.FAILURE);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章