SpringMVC 封装返回结果对象

 /***

*请求返回的最外层对象

**/

public class Result<T>{
        /*错误码*/
        private Integer code;
        /*提示信息*/
        private String msg;
        /*具体的内容*/
        private T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

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

 

/***返回对象工具类***/

public class ResultUtil {


    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }


    public static Result success() {
        return success(null);
    }


    public static Result error(Integer code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(object);
        return result;
    }

}

 

 /**给前台返回JSON数据**/

 public class ExceptionHandle{

        @ExceptionHandler(value=Exception.class)

        @ResponseBody

        public Result handle(Exception e){

            return ResultUtil.error(100,e.getMessage());

        }

    }

 

/***

*继承RuntimeException事务自动回滚

***/

    public class GirlException extends RuntimeException{

        private Integer code;

        public GirlException(Integer code,String message){
            super(message);
            this.code = code;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }
    }

 

posted @ 2017-05-26 22:13  N神3  阅读(9947)  评论(0编辑  收藏  举报