我想将表单数据直接转换为bean。最初我使用了spring,但是在我目前的项目中,我们不再使用spring了,所以我尝试做一些类似于Apache BeanUtils的帮助。我的bean看起来像这样:
public class MyBean {
private String foo;
private String bar;
private List<FooBar> fooBars;
}
public class FooBar {
private int id;
}
提交表单后,request.getParameterMap()方法给出了以下映射:
"foo" : "Some text",
"bar" : "Other text",
"foobars[0].id" : "1",
"foobars[1].id" : "2",
"foobars[2].id" : "3"
我用于转换的代码如下所示:
MyBean bean = new MyBean();
BeanUtils.populate(bean, request.getParameterMap());
使用spring数据绑定器将这些值转换为bean是没有问题的,但点符号在某种程度上不适用于BeanUtils。有谁知道输入必须如何,以便BeanUtils可以将foobars
转换为对象列表?或许你知道另一个能够做到这一点的图书馆?
BeanUtils.populate
似乎不支持嵌套属性:
此方法使用Java反射API来标识相应的“属性设置器”方法名称,并处理String,boolean,int,long,float和double类型的setter参数。此外,还可以识别这些类型(或相应的基元类型)的数组设置器。
我找到了另一种方法,BeanUtils.copyProperties
,这里指定了
如果原点“bean”实际上是Map,则假定它包含字符串值的简单属性名称作为键。
所以我想你无法用BeanUtils
做到这一点。但我可能有一个解决方案,使用PropertyUtils
。这个类有很多静态方法,其中有:
我没试过,但这是一种可行的方法:
MyBean bean = new MyBean();
for (Map.Entry<String, String> entry : request.getParameterMap())
{
try {
PropertyUtils.setProperty(bean, entry.getKey(), entry.getValue());
}
catch (NoSuchMethodException exc) {
PropertyUtils.setNestedProperty(bean, entry.getKey(), entry.getValue());
}
}
我不知道从String
到Integer
的转换是否是自动的。让我知道。