controller 返回值封装

public class Result {
	private int code;
	private String msg;
	private T data;

	/**
	 * 成功时候的调用
	 * */
	public static  Result success(T data){
		return new  Result(data);
	}
	
	/**
	 * 失败时候的调用
	 * */
	public static  Result error(CodeMsg cm){
		return new  Result(cm);
	}
	
	private Result(T data) {
		this.code = 0;
		this.msg = "success";
		this.data = data;
	}
	
	private Result(CodeMsg cm) {
		if(cm == null) {
			return;
		}
		this.code = cm.getCode();
		this.msg = cm.getMsg();
	}

	public int getCode() {
		return code;
	}
	public String getMsg() {
		return msg;
	}
	public T getData() {
		return data;
	}
}

public class CodeMsg {
	private int code;
	private String msg;
	
	public static CodeMsg SUCCESS = new CodeMsg(0, "success");
	public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常");

	
	
	private CodeMsg(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}
	
	public int getCode() {
		return code;
	}
	public String getMsg() {
		return msg;
	}
}
//调用
@RequestMapping("/success1")
    @ResponseBody
    public Result success1(){
        return Result.success("成功");
    }
    @RequestMapping("/error1")
    @ResponseBody
    public Result error1(){
        return Result.error(CodeMsg.SERVER_ERROR);
    }

你可能感兴趣的:(controller 返回值封装)