forked from gzzfw/backEnd/gz-dyh

liyj
2024-09-02 1d9d9a327ef06960189cf0e9f026904d37d01ae9
1、网关请求响应格式修改
1 files added
1 files modified
218 ■■■■■ changed files
dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java 6 ●●●●● patch | view | raw | blame | history
dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java 212 ●●●●● patch | view | raw | blame | history
dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java
@@ -1,5 +1,6 @@
package cn.huge.gateway.filter;
import cn.huge.gateway.utils.JsonMapper;
import cn.huge.gateway.utils.ReturnBO;
import cn.huge.gateway.utils.SpringContextUtil;
import com.auth0.jwt.JWT;
@@ -84,6 +85,7 @@
        if (status) {
            return chain.filter(exchange);
        } else {
            JsonMapper jsonMapper = new JsonMapper();
            ReturnBO returnBO = new ReturnBO();
            //从请求头中取出token
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");
@@ -94,7 +96,7 @@
                originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                returnBO.setCode(401);
                returnBO.setMsg("您尚未登录,请登录后重试!");
                byte[] response = returnBO.toString().getBytes(StandardCharsets.UTF_8);
                byte[] response = jsonMapper.toJson(returnBO).getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
                return originalResponse.writeWith(Flux.just(buffer));
            } else {
@@ -104,7 +106,7 @@
                    ServerHttpResponse originalResponse = exchange.getResponse();
                    originalResponse.setStatusCode(HttpStatus.OK);
                    originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                    byte[] response = returnBO.toString().getBytes(StandardCharsets.UTF_8);
                    byte[] response = jsonMapper.toJson(returnBO).getBytes(StandardCharsets.UTF_8);
                    DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
                    return originalResponse.writeWith(Flux.just(buffer));
                } else {
dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java
New file
@@ -0,0 +1,212 @@
package cn.huge.gateway.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
 * @title: JSON工具类
 * @description: JSON工具类
 * @company: hugeinfo
 * @author: liyj
 * @time: 2021-11-05 16:51:48
 * @version: 1.0.0
 */
public class JsonMapper {
    private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
    private ObjectMapper mapper;
    /**
     * 构造函数
     */
    public JsonMapper() {
        this(null);
    }
    /**
     * 构造函数
     * @param include
     */
    public JsonMapper(JsonInclude.Include include) {
        this.mapper = new ObjectMapper();
        if (include != null) {
            this.mapper.setSerializationInclusion(include);
        }
        this.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }
    /**
     * 创建非空JsonMapper
     * @return JsonMapper
     */
    public static JsonMapper nonEmptyMapper() {
        return new JsonMapper(JsonInclude.Include.NON_EMPTY);
    }
    /**
     * 创建非默认JsonMapper
     * @return JsonMapper
     */
    public static JsonMapper nonDefaultMapper() {
        return new JsonMapper(JsonInclude.Include.NON_DEFAULT);
    }
    /**
     * 对象转json字符串
     * @param object 对象
     * @return String
     */
    public String toJson(Object object) {
        try
        {
            return this.mapper.writeValueAsString(object);
        } catch (IOException e) {
            logger.warn("write to json string error:" + object, e);
        }return null;
    }
    /**
     * json字符串转对象
     * @param jsonString json字符串
     * @param clazz 类
     * @param <T> 对象
     * @return T
     */
    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try
        {
            return this.mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            logger.warn("parse json string error:" + jsonString, e);
        }return null;
    }
    /**
     * json字符串转对象
     * @param jsonString json字符串
     * @param type 类型
     * @param <T> 对象
     * @return T
     */
    public <T> T fromJson(String jsonString, TypeReference<T> type) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try
        {
            return this.mapper.readValue(jsonString, type);
        } catch (IOException e) {
            logger.warn("parse json string error:" + jsonString, e);
        }return null;
    }
    /**
     * json字符串转对象
     * @param jsonString json字符串
     * @param javaType java类型
     * @param <T> 对象
     * @return T
     */
    public <T> T fromJson(String jsonString, JavaType javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try
        {
            return this.mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            logger.warn("parse json string error:" + jsonString, e);
        }return null;
    }
    /**
     * 创建数组类型
     * @param collectionClass 数组类型
     * @param elementClasses 对象类
     * @return JavaType
     */
    public JavaType createCollectionType(Class<?> collectionClass, Class<?>[] elementClasses) {
        return this.mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
    /**
     * 更新
     * @param jsonString json字符串
     * @param object 对象
     * @return T
     */
    public <T> T update(String jsonString, T object) {
        try
        {
            return this.mapper.readerForUpdating(object).readValue(jsonString);
        } catch (JsonProcessingException e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        } catch (IOException e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        }
        return null;
    }
    /**
     * 转JsonP
     * @param functionName 函数名
     * @param object 对象
     * @return String
     */
    public String toJsonP(String functionName, Object object) {
        return toJson(new JSONPObject(functionName, object));
    }
    /**
     * 转字符串
     */
    public void enableEnumUseToString() {
        this.mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        this.mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    }
    /**
     * 获取ObjectMapper
     * @return ObjectMapper
     */
    public ObjectMapper getMapper() {
        return this.mapper;
    }
}
/**
 * -------------------_ooOoo_-------------------
 * ------------------o8888888o------------------
 * ------------------88" . "88------------------
 * ------------------(| -_- |)------------------
 * ------------------O\  =  /O------------------
 * ---------------____/`---'\____---------------
 * -------------.'  \\|     |//  `.-------------
 * ------------/  \\|||  :  |||//  \------------
 * -----------/  _||||| -:- |||||-  \-----------
 * -----------|   | \\\  -  /// |   |-----------
 * -----------| \_|  ''\---/''  |   |-----------
 * -----------\  .-\__  `-`  ___/-. /-----------
 * ---------___`. .'  /--.--\  `. . __----------
 * ------."" '<  `.___\_<|>_/___.'  >'"".-------
 * -----| | :  `- \`.;`\ _ /`;.`/ - ` : | |-----
 * -----\  \ `-.   \_ __\ /__ _/   .-` /  /-----
 * ======`-.____`-.___\_____/___.-`____.-'======
 * -------------------`=---='
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 * ---------佛祖保佑---hugeinfo---永无BUG----------
 */