WEB项目中的通用返回类
实现步骤
1.新建一个枚举类型,如下:
斜体样式枚举类型中存放着返回状态码和返回的消息,
这样做可以更加方便的添加新的返回状态码和返回信息。
public enum ResultCode{
SUCCESS(200,"操作成功"),
FAILED(500,"操作失败"),
VALIDATE_FAILED(404, "参数检验失败"),
UNAUTHORIZED(401, "暂未登录或token已经过期"),
FORBIDDEN(403, "没有相关权限");
private long code;
private String message;
private ResultCode(long code, String message) {
this.code = code;
this.message = message;
}
public long getCode() {
return code;
}
public String getMessage() {
return message;
}
}
2.新建一个通用返回类,如下:
建立此类的两个目的:
1.用来将返回状态码、返回信息和数据进行包装,将三者组装在一起
2.此类又是三个信息组装完成后的实体
注:自行包装后又将自己交出去
public class CommonResult<T> {
private long code;
private String message;
private T data;
protected CommonResult(long code,String message,T data){
this.code=code;
this.message=message;
this.data=data;
}
@Override
public String toString() {
return "CommonResult{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
public static <T> CommonResult success(T data){
return new CommonResult(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMessage(),data);
}
public static <T> CommonResult success(String message,T data){
return new CommonResult(ResultCode.SUCCESS.getCode(),message,data);
}
public static <T> CommonResult failed(){
return new CommonResult(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage(),null);
}
public static <T> CommonResult failed(String message){
return new CommonResult(ResultCode.FAILED.getCode(),message,null);
}
public static <T> CommonResult validateFailed(){
return new CommonResult(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage(),null);
}
public static <T> CommonResult validateFailed(String message){
return new CommonResult(ResultCode.VALIDATE_FAILED.getCode(),message,null);
}
public static <T> CommonResult forbidden(T data){
return new CommonResult(ResultCode.FORBIDDEN.getCode(),ResultCode.FORBIDDEN.getMessage(),data);
}
public static <T> CommonResult unauthorized(T data){
return new CommonResult(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage(),null);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
结果演示:
1.客户端发送请求
2.controller接收请求
3.service处理业务,将返回数据叫给controller
4.controller调用通用返回类静态方法组装:返回状态码、返回信息和返回数据
5.将组装后的通用返回类对象返回给客户端
@RequestMapping("/{id}")
@ResponseBody
public CommonResult getBrand(@PathVariable("id") long id){
CommonResult commonResult;
PmsBrand pmsBrand = pmsBrandService.getBrand(id);
if(pmsBrand==null){
commonResult = CommonResult.failed();
}else{
commonResult = CommonResult.success(pmsBrand);
}
return commonResult;
}
请求成功
{
"code": 200,
"message": "操作成功",
"data": {
"id": 1,
"name": "万和",
"firstLetter": "W",
"sort": 0,
"factoryStatus": 1,
"showStatus": 1,
}
}