我有以下两个简单的 POJO:
class Person {
String name
Address address;
//and of course the getter/setter for the attributes
}
class Address {
String city;
//also getter/setter for this attribute
}
还有一个支持 bean:
@ManagedBean
@RequestScoped
class PersonController {
private List persons;
private List<String> columns = Arrays.toList("name", "address.city");
//of course getter/setter
}
现在我想创建一个数据表。
<p:dataTable var="person" value="#{personController.persons}" columnIndexVar="index">
<p:columns var="column" value="#{personController.columns}">
<h:outputText value="#{person[column]}"/>
<p:columms>
</p:dataTable>
当我执行这个时,我得到一个 ServletException:
The class Person does not have the property 'address.city'.
但是,如果尝试在 p:columns 中像这样访问属性城市:
<h:outputText value="#{person.address.city}"/>
一切安好。
为什么我无法访问这样的嵌套属性
#{person['address.city']}
?以及如何在 p:columns
内访问它?
最佳答案
大括号表示法字符串表达式中的嵌套 bean 属性,如 #{person['address.city']}
默认不支持。你基本上需要一个 #{person['address']['city']}
.
您需要定制 ELResolver
这里。最简单的是扩展现有的 BeanELResolver
.
这是一个启动示例:
public class ExtendedBeanELResolver extends BeanELResolver {
@Override
public Object getValue(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException
{
if (property == null || base == null || base instanceof ResourceBundle || base instanceof Map || base instanceof Collection) {
return null;
}
String propertyString = property.toString();
if (propertyString.contains(".")) {
Object value = base;
for (String propertyPart : propertyString.split("\\.")) {
value = super.getValue(context, value, propertyPart);
}
return value;
}
else {
return super.getValue(context, base, property);
}
}
}
要让它运行,请在
faces-config.xml
中按如下方式注册它:<application>
<el-resolver>com.example.ExtendedBeanELResolver</el-resolver>
</application>
关于jsf - 无法访问 p :columns 内托管 bean 中的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10722255/