为了规范后台开发接口的标准,以及便于前台统一处理接口返回数据,定义一个通用的返回类是必要的。
@ApiModel("统一的返回类型")
public class ResultBean<T> {
private static String SUCCESS_CODE="0";
private static String ERROR_CODE="1";
private static String REFUSED_CODE="2";
public ResultBean(T data){
this.data = data;
}
/**
* 执行结果:0成功1失败
*/
@ApiModelProperty("结果代码:0成功1失败")
private String code;
/**
* 描述(错误原因)
*/
@ApiModelProperty("失败原因")
private String message;
/**
* 返回对象
*/
@ApiModelProperty("返回结果的json")
private T data;
public ResultBean success(){
this.code = SUCCESS_CODE;
return this;
}
public ResultBean failed(String errorMessage){
this.data = null;
this.code = ERROR_CODE;
this.message = errorMessage;
return this;
}
public ResultBean refused(){
this.data = null;
this.code = REFUSED_CODE;
return this;
}
//getter and setter
}
Controller层示例
@ApiOperation(value = "查看", notes = "")
@ResponseBody
@RequestMapping(value = "/view", method = {RequestMethod.GET})
public ResultBean<YourBean> view(String id) {
try {
return new ResultBean(service.findById(id)).success();
} catch (Exception e) {
logger.error("",e);
return new ResultBean(null).failed(e.getMessage());
}
}