修改时间:2020-08-15
假设后台 controller 的参数是一个 User 类型的变量,User 的定义如下:
public class User {
private String name;
private int age;
private List novels;
private List tags;
private String[] comments;
private Blog blog;
Map 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
如果前端使用的是 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)
})