public class Result<T> {
private Integer code;
private String msg;
private T data;
public Result() {
super();
}
public Result(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = 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;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
public enum ResultEnum {
//这里是可以自己定义的,方便与前端交互即可
UNKNOWN_ERROR(-1,"未知错误"),
SUCCESS(200,"成功"),
SERVER_INTERNAL_ERROR(500,"服务器内部错误"),
RESOURCE_NOT_FOUND(404,"资源未找到"),
PARAMETER_NOT_VALID(400,"参数不合法"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
public class ResultUtil {
/**成功且带数据**/
public static Result success(Object object){
Result result = new Result();
result.setCode(ResultEnum.SUCCESS.getCode());
result.setMsg(ResultEnum.SUCCESS.getMsg());
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);
return result;
}
}
//测试
@RequestMapping(value = "/list", method = RequestMethod.POST)
public Result findCategoryByPid(@RequestBody Map map){
map.get("parentId");
List<Category> list = categoryService.findCategoryByPid(map);
if (CollectionUtils.isEmpty(list)){
return ResultUtil.error(404,"资源未找到到");
}
return ResultUtil.success(list);
}
java返回数据的封装
点赞
收藏