Skip to content

通用的泛型服务端响应对象

可放在 src \ main \ java \ com \ 二级包名 \ common 目录下

静态信息 —— ResponseCode.java

  • 响应的code值和对应的信息, 可自己修改、添加、删除
java
public enum ResponseCode {

    SUCCESS(0, "SUCCESS"),
    UNKNOW_ERROR(1, "未知错误"),
    NO_HANDLER_FOUND(1, "找不到执行的路径操作"),
    BIND_EXCEPTION_ERROR(1,"请求参数错误");

    private final int code;
    private final String desc;

    ResponseCode(int code, String desc){
        this.code = code;
        this.desc = desc;
    }

    public int getCode(){
        return code;
    }

    public String getDesc(){
        return desc;
    }
}

方法 —— ServerResponse.java

  1. 添加依赖

    xml
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.12</version>
    </dependency>
  2. 响应的结果

    java
    import org.codehaus.jackson.annotate.JsonIgnore;
    import org.codehaus.jackson.map.annotate.JsonSerialize;
    import java.io.Serializable;
    
    @JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)
    //保证序列化json的时候,如果是null的对象,key也会消失
    public class ServerResponse<T> implements Serializable {
    
        private int code;
        private String msg;
        private T data;
    
        private ServerResponse(int code){
            this.code = code;
        }
        private ServerResponse(int code,T data){
            this.code = code;
            this.data = data;
        }
    
        private ServerResponse(int code,String msg,T data){
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
    
        private ServerResponse(int code,String msg){
            this.code = code;
            this.msg = msg;
        }
    
        @JsonIgnore
        //使之不在json序列化结果当中
        public boolean isSuccess(){
            return this.code == ResponseCode.SUCCESS.getCode();
        }
    
        public int getCode(){
            return code;
        }
        public T getData(){
            return data;
        }
        public String getMsg(){
            return msg;
        }
    
        public static <T> ServerResponse<T> createBySuccess(){
            return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
        }
    
        public static <T> ServerResponse<T> createBySuccessMessage(String msg){
            return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
        }
    
        public static <T> ServerResponse<T> createBySuccess(T data){
            return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
        }
    
        public static <T> ServerResponse<T> createBySuccess(String msg,T data){
            return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
        }
    
        public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){
            return new ServerResponse<T>(errorCode,errorMessage);
        }
    
        public static <T> ServerResponse<T> createByGlobalError(ResponseCode responseCode){
            return new ServerResponse<T>(responseCode.getCode(), responseCode.getDesc());
        }
    }

全局错误处理 —— GlobalExceptionHandler

  1. 添加依赖

    xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
  2. 全局处理

    java
    import org.springframework.web.bind.ServletRequestBindingException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.NoHandlerFoundException;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public ServerResponse doError(HttpServletRequest servletRequest, HttpServletResponse httpServletResponse, Exception ex){
            if (ex instanceof  Exception) {
                // throw 的错误
                return ServerResponse.createByErrorCodeMessage(1, ex.getMessage());
            } else if (ex instanceof NoHandlerFoundException) {
                // url 不匹配
                return ServerResponse.createByGlobalError(ResponseCode.NO_HANDLER_FOUND);
            } else if (ex instanceof ServletRequestBindingException) {
                // 参数字段不匹配
                return ServerResponse.createByGlobalError(ResponseCode.BIND_EXCEPTION_ERROR);
            } else {
                // 其他错误
                return ServerResponse.createByGlobalError(ResponseCode.UNKNOW_ERROR);
            }
        }
    }
  3. application.properties 添加配置

    properties
    # 不匹配 url 时,不适用静态文件返回,则可返回上面的错误 json
    spring.resources.add-mappings=false
    spring.mvc.throw-exception-if-no-handler-found=true

使用例子

  1. 只传status

    java
    ServerResponse.createBySuccess()
    ServerResponse.createByError()
    ServerResponse.createByErrorCodeMessage(自定义code, "") // 这个会带个空字符串

    返回

    json
    {
    	status: 
    }
  2. 传 status 和 msg

    java
    ServerResponse.createBySuccessMessage("信息")
    ServerResponse.createByErrorCodeMessage("信息")
    ServerResponse.createByErrorCodeMessage(自定义code, "信息")

    返回

    json
    {
    	status: ,
    	msg:
    }
  3. 传 status 和 data

    java
    ServerResponse.createBySuccess(数据)

    返回

    json
    {
    	status: ,
    	data:
    }
  4. 传 status 和 msg 和 data

    java
    ServerResponse.createBySuccess("信息", 数据)

    返回

    json
    {
    	status: ,
    	mag: ,
    	data:
    }