2016-02-05 33 views
0

我休息端点(弹簧引导1.3.0-RELEASE - >弹簧芯4.2.4.RELEASE),这需要多重实例字符串参数Spring框架REST多值请求参数空数组

@RequestMapping(value = "/test", method = RequestMethod.GET) 
public ResponseEntity<Object> getTest(@RequestParam(value = "testParam", required = false) String[] testParamArray) {} 

/test?testParam= => testParamArray has length 0 
/test?testParam=&testParam= => testParamArray has length 2 (two empty string items) 

我期望第一种情况在数组中获得单个空sting元素,但没有。 关于如何实现这一点的任何想法?

+0

检查您的浏览器或http客户端是否不放弃空参数。 – JVXR

+0

我不认为这是事实。当使用类似@RequestParam Map params的东西时,我在那里看到单个null值(?testParam =) – silverdrop

回答

1

Spring的StringToArrayConverter负责此转换。如果你看看它的convert方法:

public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { 
     if (source == null) { 
      return null; 
     } 
     String string = (String) source; 
     String[] fields = StringUtils.commaDelimitedListToStringArray(string); 
     Object target = Array.newInstance(targetType.getElementTypeDescriptor().getType(), fields.length); 
     for (int i = 0; i < fields.length; i++) { 
      String sourceElement = fields[i]; 
      Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, targetType.getElementTypeDescriptor()); 
      Array.set(target, i, targetElement); 
     } 
     return target; 
} 

基本上,它需要输入(空String你的情况),由逗号分割它,并与爆炸String的值返回数组。当然,拆分空的String的结果是空的Array

当您传递两个具有相同名称的参数时,将调用ArrayToArrayConverter,它的行为与您预期的相同,并返回一个包含两个空的String的数组。

如果要禁用默认StringArray行为,要注册另一个Converter一个空String转换成一个单一的元素Array

+1

谢谢Ali。我现在明白这个问题。 – silverdrop