springboot get请求传递json对象(含值为对象的属性),映射到后台Controller参数实体的 Map 类型字段(含相关关键源码)

修改时间:2020-08-15

假设后台 controller 的参数是一个 User 类型的变量,User 的定义如下:

public class User {
    private String name;
    private int age;
    private List<Novel> novels;
    private List<String> tags;
    private String[] comments;
    private Blog blog;
    Map<string, Object> params;
}
public class Novel {
    private String name;
    private int size;
}

 

public class Blog {
    private String title;
    private Author author;
}

前台的 json 要使用以下写法:

{
    name: '22',
    'params[age]': '21',
    'params[weight]': 60,
    'tags[1]': 't1',
    'tags[3]': 't3',
    'comments[1]': 'c1',
    'comments[3]': 'c3',
    'blog.title': 'bt1',
    'novels[4].name': 'nv4'
}

如果后台报错说请求链接包含非法字符,则用 encodeURIComponent 编码,或者直接手动写死也行,'[' 是 '%5B', ']' 是 '%5D'。原因是get请求参数和值都是拼接在URL里的,默认情况下是不允许含有这些字符的。以下是部分关键源码:

以下代码指明了为什么是 '['  ']'  '.':

// PropertyAccessorUtils.java
private static int getNestedPropertySeparatorIndex(String propertyPath, boolean last) {
    boolean inKey = false;
    int length = propertyPath.length();
    int i = (last ? length - 1 : 0);
    while (last ? i >= 0 : i < length) {
        switch (propertyPath.charAt(i)) {
            case PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR:
            case PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR:
                inKey = !inKey;
                break;
            case PropertyAccessor.NESTED_PROPERTY_SEPARATOR_CHAR:
                if (!inKey) {
                    return i;
                }
        }
        if (last) {
            i--;
        }
        else {
            i++;
        }
    }
    return -1;
}

// PropertyAccessor.java
public interface PropertyAccessor {
	/**
	 * Path separator for nested properties.
	 * Follows normal Java conventions: getFoo().getBar() would be "foo.bar".
	 */
	String NESTED_PROPERTY_SEPARATOR = ".";

	/**
	 * Path separator for nested properties.
	 * Follows normal Java conventions: getFoo().getBar() would be "foo.bar".
	 */
	char NESTED_PROPERTY_SEPARATOR_CHAR = '.';

	/**
	 * Marker that indicates the start of a property key for an
	 * indexed or mapped property like "person.addresses[0]".
	 */
	String PROPERTY_KEY_PREFIX = "[";

	/**
	 * Marker that indicates the start of a property key for an
	 * indexed or mapped property like "person.addresses[0]".
	 */
	char PROPERTY_KEY_PREFIX_CHAR = '[';

	/**
	 * Marker that indicates the end of a property key for an
	 * indexed or mapped property like "person.addresses[0]".
	 */
	String PROPERTY_KEY_SUFFIX = "]";

	/**
	 * Marker that indicates the end of a property key for an
	 * indexed or mapped property like "person.addresses[0]".
	 */
	char PROPERTY_KEY_SUFFIX_CHAR = ']';
}

以下代码说明了可以处理的集合类型:

// AbstractNestablePropertyAccessor.java
private void processKeyedProperty(PropertyTokenHolder tokens, PropertyValue pv) {
    Object propValue = getPropertyHoldingValue(tokens);
    PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
    if (ph == null) {
        throw new InvalidPropertyException(
                getRootClass(), this.nestedPath + tokens.actualName, "No property handler found");
    }
    Assert.state(tokens.keys != null, "No token keys");
    String lastKey = tokens.keys[tokens.keys.length - 1];

    if (propValue.getClass().isArray()) {
        Class<?> requiredType = propValue.getClass().getComponentType();
        int arrayIndex = Integer.parseInt(lastKey);
        Object oldValue = null;
        try {
            if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                oldValue = Array.get(propValue, arrayIndex);
            }
            Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                    requiredType, ph.nested(tokens.keys.length));
            int length = Array.getLength(propValue);
            if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) {
                Class<?> componentType = propValue.getClass().getComponentType();
                Object newArray = Array.newInstance(componentType, arrayIndex + 1);
                System.arraycopy(propValue, 0, newArray, 0, length);
                setPropertyValue(tokens.actualName, newArray);
                propValue = getPropertyValue(tokens.actualName);
            }
            Array.set(propValue, arrayIndex, convertedValue);
        }
        catch (IndexOutOfBoundsException ex) {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                    "Invalid array index in property path '" + tokens.canonicalName + "'", ex);
        }
    }

    else if (propValue instanceof List) {
        Class<?> requiredType = ph.getCollectionType(tokens.keys.length);
        List<Object> list = (List<Object>) propValue;
        int index = Integer.parseInt(lastKey);
        Object oldValue = null;
        if (isExtractOldValueForEditor() && index < list.size()) {
            oldValue = list.get(index);
        }
        Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                requiredType, ph.nested(tokens.keys.length));
        int size = list.size();
        if (index >= size && index < this.autoGrowCollectionLimit) {
            for (int i = size; i < index; i++) {
                try {
                    list.add(null);
                }
                catch (NullPointerException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                            "Cannot set element with index " + index + " in List of size " +
                            size + ", accessed using property path '" + tokens.canonicalName +
                            "': List does not support filling up gaps with null elements");
                }
            }
            list.add(convertedValue);
        }
        else {
            try {
                list.set(index, convertedValue);
            }
            catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                        "Invalid list index in property path '" + tokens.canonicalName + "'", ex);
            }
        }
    }

    else if (propValue instanceof Map) {
        Class<?> mapKeyType = ph.getMapKeyType(tokens.keys.length);
        Class<?> mapValueType = ph.getMapValueType(tokens.keys.length);
        Map<Object, Object> map = (Map<Object, Object>) propValue;
        // IMPORTANT: Do not pass full property name in here - property editors
        // must not kick in for map keys but rather only for map values.
        TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
        Object convertedMapKey = convertIfNecessary(null, null, lastKey, mapKeyType, typeDescriptor);
        Object oldValue = null;
        if (isExtractOldValueForEditor()) {
            oldValue = map.get(convertedMapKey);
        }
        // Pass full property name and old value in here, since we want full
        // conversion ability for map values.
        Object convertedMapValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                mapValueType, ph.nested(tokens.keys.length));
        map.put(convertedMapKey, convertedMapValue);
    }

    else {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                "Property referenced in indexed property path '" + tokens.canonicalName +
                "' is neither an array nor a List nor a Map; returned value was [" + propValue + "]");
    }
}

 

如果前端使用的是 Vue,那么可以在 request 拦截器里统一处理。既然要处理,那么前端就改用一种更符合直觉的方式:

{
    name: '22',
    params: {
        age: '21',
        weight: 60
    }
}

然后在 request 拦截器里做转换和编码(只处理了对象,没有处理数组)参考 axios不会对url中的功能性字符进行编码

service.interceptors.request.use(config => {
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  
  let url = config.url;
  if (config.method === 'get' && config.params) {
    url += '?';
    let keys = Object.keys(config.params);
    for (const key of keys) {
      const value = config.params[key];
      if (typeof value === 'object') {
        for (const key2 of Object.keys(value)) {
          let key3 = key + '[' + key2 + ']';
          url += `${encodeURIComponent(key3)}=${value[key2] == undefined ? '' : encodeURIComponent(value[key2])}&`;
        }
      } else {
        url += `${encodeURIComponent(key)}=${config.params[key] == undefined ? '' : encodeURIComponent(config.params[key])}&`;
      }
    }
    url = url.substring(0, url.length - 1);
    config.params = {};
  }
  config.url = url;
  
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值