【Java Web】项目通用返回模块ServerResponse:枚举code状态码、泛型返回值、序列化注解限制数据
一、枚举类编写ResponseCode
package com.boulderaitech.common;
/**
* 编写枚举类的步骤
* (1)编写所需的变量
* (2)编写枚举类构造方法
* (3)编写枚举的值,调用构造方法,使用逗号隔开
* (4)编写方法获取枚举类中对应的值
*/
public enum ResponseCode {
//(3)编写枚举的值,调用构造方法,使用逗号隔开
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR");
//(1)编写所需的变量
private final int code;
private final String desc;
//(2)编写枚举类构造方法
ResponseCode(int code,String desc) {
this.code=code;
this.desc=desc;
}
//(4)编写方法获取枚举类中对应的值
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
二、含泛型的通用返回类ServerResponse
package com.boulderaitech.common;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.Serializable;
//用于封装数据的类,加泛型实现序列化接口
//通过注解约束其序列化方式,即非空的类不允许序列化
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
//编写不同的构造方法,更改为private,禁止外部创建该类的对象
private ServerResponse(int status) {
this.status = status;
}
private ServerResponse(int status, String msg) {
this.status = status;
this.msg = msg;
}
private ServerResponse(int status, T data) {
this.status = status;
this.data = data;
}
private ServerResponse(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
//提供get方法,后续要返回json数据,没有get方法无法返回数据
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
//在内部提供静态方法供外部访问
public static <T> ServerResponse<T> createSuccess() {
return new ServerResponse<>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServerResponse<T> createSuccessMsg(String msg) {
return new ServerResponse<>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ServerResponse<T> createSuccessData(T data) {
return new ServerResponse<>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> ServerResponse<T> createSuccessMsgData(String msg,T data) {
return new ServerResponse<>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ServerResponse<T> createErrorMsg(String errorMsg) {
return new ServerResponse<>(ResponseCode.ERROR.getCode(),errorMsg);
}
}
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/16884182.html