这节记录下如何使用枚举类和响应封装类实现响应结果封装。
第一步:新建立一个枚举类。枚举类的要求有两个变量,响应码code,响应信息desc。响应码需要跟前端约定好。
public enum ResponseCode {
SUCCESS("success",101),
ERROR("error",102),
ILLEGAL_ARGUMENT("illegal_argument",103);
private final int code;
private final String desc;
ResponseCode(String desc, int code){
this.desc = desc;
this.code = code;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
第二步:新建一个泛型类
package cn.wcyf.wcai.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.Serializable;
/**
* created by mero on 2018/3/13.<br>
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ResponseObject<T> implements Serializable{
private Integer code;
private String msg;
private T data;
private ResponseObject(int code){
this.code = code;
}
private ResponseObject(int code, String msg){
this.code = code;
this.msg = msg;
}
private ResponseObject(int code, String msg, T data){
this.code = code;
this.msg = msg;
this.data = data;
}
private ResponseObject(int code, T data){
this.code = code;
this.data = data;
}
public void setStatus(int code){
this.code = code;
}
public int getStatus(){
return code;
}
public void setMsg(String msg){
this.msg = msg;
}
public String getMsg(){
return msg;
}
public void setData(T data){
this.data = data;
}
public T getData(){
return data;
}
public static <T> ResponseObject<T> createSuccessfulResp(){
return new ResponseObject<T>(ResponseCode.SUCCESS.getCode());
}
private static <T> ResponseObject<T> createSuccessfulResp(String msg){
return new ResponseObject<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ResponseObject<T> createSuccessfulResp(String msg,T data){
return new ResponseObject<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ResponseObject<T> createSuccessfulResp(T data){
return new ResponseObject<T>(ResponseCode.SUCCESS.getCode(),data);
}
public <T> ResponseObject<T> createErrorResp(){
return new ResponseObject<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static <T> ResponseObject<T> createErrorResp(String msg){
return new ResponseObject<T>(ResponseCode.ERROR.getCode(),msg);
}
public static <T> ResponseObject<T> createErrorResp(int code,String desc){
return new ResponseObject<T>(code,desc);
}
public static <T> ResponseObject<T> createDescAndCodeResp(String desc,int code){
return new ResponseObject<T>(code,desc);
}
@JsonIgnore
public boolean isSuccess(){
return this.code == ResponseCode.SUCCESS.getCode();
}
}
第三步:测试
在controller中编写一个函数测试
/**
* 通过id查询指定学生信息
* @param id
* @return
*/
@GetMapping("/{id}")
public ResponseObject<Student> getById(@PathVariable Integer id){
if(id==10||id==11){
return ResponseObject.createSuccessfulResp(ResponseCode.SUCCESS.getDesc(),studentService.getById(id));
}
return ResponseObject.createErrorResp(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
测试结果如下: