Web统一返回值封装代码

Web统一返回值封装代码

本文是记录在开发过程中使用的一种统一返回值的封装代码,具体代码如下:

package com.frame.yihao.base.response.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.frame.yihao.base.response.enumeration.HttpStatusEnum;
import com.frame.yihao.base.response.enumeration.ResponseMessageEnum;
import com.frame.yihao.base.response.enumeration.SystemStatusEnum;
import com.google.common.collect.Sets;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author: darryl
 * @Date: 2019/12/26 13:20
 * 返回值统一封装
 */
@Data
@ApiModel("系统返回值统一封装")
public class ResponseMessage<T> implements Serializable {

    /**
     * 异常消息
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty("异常消息")
    protected String message;

    /**
     * 业务状态码
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty("业务状态码")
    protected String code;

    /**
     * 响应值
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty("响应值")
    protected T result;

    /**
     * 状态码
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value = "状态码", required = true)
    protected int status;

    /**
     * 响应内容的字段
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty("响应内容的字段")
    protected LinkedHashSet<String> fields;

    /**
     * 时间戳
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value = "时间戳", required = true, dataType = "Long")
    protected Long timestamp;

    /**
     * 包括
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(hidden = true)
    protected transient Map<Class<?>, Set<String>> includes;

    /**
     * 排除
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(hidden = true)
    protected transient Map<Class<?>, Set<String>> excludes;

    /**
     * 业务逻辑异常
     *
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> serviceException(String message) {
        return error(HttpStatusEnum.OK.getValue(), SystemStatusEnum.UNKNOWN.getCode(), message);
    }

    /**
     * 用户未登录
     *
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> unLogin() {
        return error(HttpStatusEnum.OK.getValue(), SystemStatusEnum.NOLOGGING.getCode(), ResponseMessageEnum.USER_UN_LOGIN.getCode());
    }

    /**
     * 无权限,需要消息提示
     *
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> unauthorized(String message) {
        return error(HttpStatusEnum.OK.getValue(), SystemStatusEnum.UNAUTHORIZED.getCode(), message);
    }

    /**
     * 无权限
     *
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> unauthorized() {
        return error(HttpStatusEnum.OK.getValue(), SystemStatusEnum.UNAUTHORIZED.getCode(), ResponseMessageEnum.NO_ACCESS.getCode());
    }

    /**
     * 请求失败,包含失败消息
     *
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(String message) {
        return error(HttpStatusEnum.INTERNAL_SERVER_ERROR.getValue(), SystemStatusEnum.UNKNOWN.getCode(), message);
    }

    /**
     * 请求失败。包含失败消息与失败消息args
     *
     * @param message
     * @param args
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(String message, Object... args) {
        return error(HttpStatusEnum.INTERNAL_SERVER_ERROR.getValue(), message, args);
    }

    /**
     * 请求失败
     *
     * @param status
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(int status, String message) {
        return error(status, SystemStatusEnum.UNKNOWN.getCode(), message);
    }

    /**
     * 请求失败
     *
     * @param status
     * @param message
     * @param args
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(int status, String message, Object... args) {
        return error(status, SystemStatusEnum.UNKNOWN.getCode(), message, args);
    }

    /**
     * 请求失败
     *
     * @param status
     * @param code
     * @param message
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(int status, String code, String message) {
        return error(status, code, message, null);
    }

    /**
     * 请求失败
     *
     * @param status
     * @param code
     * @param message
     * @param args
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> error(int status, String code, String message, Object... args) {
        ResponseMessage<T> msg = new ResponseMessage<>();
        msg.message = message;
        msg.status(status);
        msg.code(code);
        return msg.putTimeStamp();
    }

    /**
     * 请求成功,不包含响应值
     */
    public static <T> ResponseMessage<T> ok() {
        return ok(null);
    }

    /**
     * 请求成功,包含响应值
     *
     * @param result
     * @param <T>
     * @return
     */
    public static <T> ResponseMessage<T> ok(T result) {
        return (new ResponseMessage<T>()).result(result).putTimeStamp().code(SystemStatusEnum.SUCCESS.getCode()).status(HttpStatusEnum.OK.getValue());
    }

    /**
     * 设置响应值
     *
     * @param status
     * @return
     */
    public ResponseMessage<T> status(int status) {
        this.status = status;
        return this;
    }

    /**
     * 设置业务逻辑代码
     *
     * @param code
     * @return
     */
    public ResponseMessage<T> code(String code) {
        this.code = code;
        return this;
    }

    /**
     * 设置结果值
     *
     * @param result
     * @return
     */
    public ResponseMessage<T> result(T result) {
        this.result = result;
        return this;
    }

    /**
     * 设置时间戳
     *
     * @return
     */
    private ResponseMessage<T> putTimeStamp() {
        this.timestamp = System.currentTimeMillis();
        return this;
    }

    /**
     * 响应内容字段
     *
     * @param fields
     * @return
     */
    public ResponseMessage<T> fields(LinkedHashSet<String> fields) {
        this.fields = fields;
        return this;
    }

    /**
     * 相应内容字段组
     *
     * @param field
     * @return
     */
    public ResponseMessage<T> field(String field) {
        if (this.fields == null) {
            synchronized (this) {
                if (this.fields == null) {
                    this.fields = Sets.newLinkedHashSet();
                }
            }
        }
        this.fields.add(field);
        return this;
    }

    /**
     * 重写toString
     *
     * @return
     */
    @Override
    public String toString() {
        return JSON.toJSONStringWithDateFormat(this, "yyyy-MM-dd HH:mm:ss", new com.alibaba.fastjson.serializer.SerializerFeature[0]);
    }

    /**
     * @param type
     * @param fields
     * @return
     */
    public ResponseMessage<T> include(Class<?> type, String... fields) {
        return include(type, Arrays.asList(fields));
    }

    /**
     * @param type
     * @param fields
     * @return
     */
    public ResponseMessage<T> include(Class<?> type, Collection<String> fields) {
        if (this.includes == null) {
            this.includes = new HashMap<>();
        }
        if (fields == null || fields.isEmpty()) {
            return this;
        }
        fields.forEach(field -> {
            if (field.contains(".")) {
                String[] tmp = field.split("[.]", 2);
                try {
                    Field field1 = type.getDeclaredField(tmp[0]);
                    if (field1 != null) {
                        include(field1.getType(), new String[]{tmp[1]});
                    }
                } catch (Throwable throwable) {
                }
            } else {

                getStringListFromMap(this.includes, type).add(field);
            }
        });
        return this;
    }

    /**
     * @param type
     * @param fields
     * @return
     */
    public ResponseMessage<T> exclude(Class type, Collection<String> fields) {
        if (this.excludes == null) {
            this.excludes = new HashMap<>();
        }
        if (fields == null || fields.isEmpty()) {
            return this;
        }
        fields.forEach(field -> {
            if (field.contains(".")) {
                String[] tmp = field.split("[.]", 2);
                try {
                    Field field1 = type.getDeclaredField(tmp[0]);
                    if (field1 != null) {
                        exclude(field1.getType(), new String[]{tmp[1]});
                    }
                } catch (Throwable throwable) {
                }
            } else {

                getStringListFromMap(this.excludes, type).add(field);
            }
        });
        return this;
    }

    /**
     * @param fields
     * @return
     */
    public ResponseMessage<T> exclude(Collection<String> fields) {
        Class<?> type;
        if (this.excludes == null) {
            this.excludes = new HashMap<>();
        }
        if (fields == null || fields.isEmpty()) {
            return this;
        }

        if (getResult() != null) {
            type = getResult().getClass();
        } else {
            return this;
        }
        exclude(type, fields);
        return this;
    }

    /**
     * @param fields
     * @return
     */
    public ResponseMessage<T> include(Collection<String> fields) {
        Class<?> type;
        if (this.includes == null) {
            this.includes = new HashMap<>();
        }
        if (fields == null || fields.isEmpty()) {
            return this;
        }

        if (getResult() != null) {
            type = getResult().getClass();
        } else {
            return this;
        }
        include(type, fields);
        return this;
    }

    /**
     * @param type
     * @param fields
     * @return
     */
    public ResponseMessage<T> exclude(Class type, String... fields) {
        return exclude(type, Arrays.asList(fields));
    }

    /**
     * @param fields
     * @return
     */
    public ResponseMessage<T> exclude(String... fields) {
        return exclude(Arrays.asList(fields));
    }

    /**
     * @param fields
     * @return
     */
    public ResponseMessage<T> include(String... fields) {
        return include(Arrays.asList(fields));
    }

    /**
     * @param map
     * @param type
     * @return
     */
    protected Set<String> getStringListFromMap(Map<Class<?>, Set<String>> map, Class<?> type) {
        return map.computeIfAbsent(type, k -> new HashSet());
    }
}


希望对您有帮助。

文章推荐:教你搭建多模块系统

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
教学-传智播客-项目视频经典之作巴巴运动网106集-28将Web层分页封装成通用模块源代码 所需要的jar文件: (一)、Hibernate: 位于 "\hibernate-distribution-3.3.2.GA" 目录下的jar文件: hibernate3.jar 位于 "\hibernate-distribution-3.3.2.GA\lib\required" 目录下的jar文件: (共7个) antlr-2.7.6.jar commons-collections-3.1.jar dom4j-1.6.1.jar javassist-3.9.0.GA.jar jta-1.1.jar slf4j-api-1.5.8.jar slf4j-nop-1.5.2.jar (二)、JPA: 位于 "\Hibernate\hibernate-entitymanager3.4.0.GA" 目录下的jar文件: hibernate-entitymanager.jar ejb3-persistence.jar hibernate-annotations.jar hibernate-commons-annotations.jar (三)、Spring: 位于 "\spring-framework-2.5.5\dist" 目录下的jar文件: spring.jar 位于 "\spring-framework-2.5.5\lib\aspectj" 目录下的jar文件: (共3个) aspectjrt.jar aspectjweaver.jar 位于 "\spring-framework-2.5.5\lib\cglib" 目录下的jar文件: (共1个) cglib-nodep-2.1_3.jar 位于 "\spring-framework-2.5.5\lib\j2ee\" 目录下的jar文件: common-annotations.jar 位于 "\spring-framework-2.5.5\lib\jakarta-commons" 目录下的jar文件: commons-dbcp.jar commons-pool.jar commons-logging.jar (四)、Struts: 位于 "\Struts\struts-1.3.10\struts-1.3.10-all\struts-1.3.10\lib" 目录下的jar文件: (共20个) antlr-2.7.2.jar(与Hibernate所含antlr-2.7.6.jar文件重复,删除) bsf-2.3.0.jar commons-beanutils-1.8.0.jar commons-chain-1.2.jar commons-digester-1.8.jar commons-fileupload-1.1.1.jar commons-io-1.1.jar commons-logging-1.0.4.jar commons-validator-1.3.1.jar jstl-1.0.2.jar(改为:\spring-framework-2.5.5\lib\j2ee\jstl.jar) oro-2.0.8.jar standard-1.0.6.jar(改为:\spring-framework-2.5.5\lib\jakarta-taglibs\standard.jar) struts-core-1.3.10.jar struts-el-1.3.10.jar struts-extras-1.3.10.jar struts-faces-1.3.10.jar struts-mailreader-dao-1.3.10.jar struts-scripting-1.3.10.jar struts-taglib-1.3.10.jar struts-tiles-1.3.10.jar (五)、Spring+Struts: \spring-framework-2.5.5\dist\modules\spring-webmvc-struts.jar MySQL: mysql-connector-java-5.1.16-bin.jar 运行: http://localhost:8090/control/center/main.do

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dp_shiyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值