[英]How to handle multidimensional array as @RequestParam in Spring MVC?
[英]Spring MVC REST requestParam to handle multiple values for the same key
我正在执行GET请求,它有2个参数或基本上是一个数组
param {
paramNo:1,
from:mobile,
to:server
}
param {
paramNo:2,
from:server,
to:mobile
}
在我的控制器中,我已将其捕获为
public @ResponseBody SearchResponse serverSearch(@RequestParam List<String> param) throws Exception {
ObjectMapper mapper = new ObjectMapper();
List<SearchInfo> searchInfo = mapper.readValue(param,new TypeReference<List<SearchInfo>>(){});
}
mapper.readValue不接受列表。 它抛出编译错误。
题
最初 ,您将不得不使用数组而不是列表 ,但是您可以轻松地执行以下操作: List<SearchInfo> params = Arrays.asList(myArray);
如果您的参数是有效的JSON(如您的示例所示),则将其转换为自定义对象非常简单,请参见此处 。
否则,您可以使用Spring创建一个自定义格式化程序,该格式化程序会将来自请求参数的字符串格式化为自定义对象。 基本上,您首先必须创建一个类,该类注册要格式化的对象的类型以及进行格式化的类:
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;
public class SearchInfoFormatterRegistrar implements FormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldType(SearchInfo.class, new SearchInfoFormatter());
}
}
然后实现进行格式化的类(请注意,这不仅仅是将对象转换为其他类型,您实际上必须使用一些逻辑):
import org.springframework.format.Formatter;
public class SearchInfoFormatter implements Formatter<SearchInfo> {
@Override
public String print(SearchInfo info, Locale locale) {
// Format SearchInfo into String here.
}
@Override
public SearchInfo parse(String text, Locale locale) {
// Format String into SearchInfo here.
}
}
最后,将它们添加到配置中:
<bean name="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<bean class="org.my.SearchInfoFormatterRegistrar" />
</set>
</property>
</bean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.