问题描述
我有以下两个简单的 POJO:
I have following two simple POJOs:
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:
And a backing bean:
@ManagedBean
@RequestScoped
class PersonController {
private List persons;
private List<String> columns = Arrays.toList("name", "address.city");
//of course getter/setter
}
现在我想创建一个数据表.
Now I want to create a dataTable.
<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:
When I execute this I get a ServletException:
Person 类没有属性address.city".
但是如果尝试在 p:columns 中像这样访问属性城市:
But if a try to access the property city like this within p:columns:
<h:outputText value="#{person.address.city}"/>
一切正常.
为什么我不能访问像 #{person['address.city']}
这样的嵌套属性?我如何在 p:columns
中访问它?
Why I can not access a nested property like that #{person['address.city']}
? And how can I access it within p:columns
?
推荐答案
默认情况下不支持在大括号表示法字符串表达式中嵌套 bean 属性,例如 #{person['address.city']}
.你基本上需要一个#{person['address']['city']}
.
Nested bean properties in a brace notation string expression like #{person['address.city']}
is by default not supported. You basically need a #{person['address']['city']}
.
您需要一个自定义的 ELResolver
在这里.最简单的方法是扩展现有的BeanELResolver
.
You need a custom ELResolver
here. Easiest is to extend the existing 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
中注册如下:
To get it to run, register it as follows in faces-config.xml
:
<application>
<el-resolver>com.example.ExtendedBeanELResolver</el-resolver>
</application>
这篇关于无法访问 p:columns 中托管 bean 中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!