gpt4 book ai didi

jsf - F :selectItems showing the class not a value

转载 作者:行者123 更新时间:2023-12-05 01:19:25 24 4
gpt4 key购买 nike

我是 facelets 的新手,我已经使用 netbeans 生成了一个项目,但我在标签上苦苦挣扎。

我有

<h:selectOneMenu id="country" value="#{organisation.organisation.country}" title="Country" >
<f:selectItems value="#{country.countryItemsAvailableSelectOne}"/>
</h:selectOneMenu>

在选择中,我得到 classpath.Country[iso=GB] ,我可以看到它是一个对象,但我真的很想看到 country.prinableName 值。
我看了半天,画了一个空白
谢谢你的帮助

最佳答案

由于您在谈论 Facelets,我将假设 JSF 2.x。

首先,HTML 是一个完整的字符串。 JSF 生成 HTML。默认情况下,非 String Java 对象来自 toString()方法转换为他们的String JSF 生成 HTML 时的表示。在这些 Java 对象和 String 之间正确转换, 你需要一个 Converter .

我假设您的 Country对象已经有 equals()方法properly implemented ,否则验证将在稍后失败,并显示“验证错误:值无效”,因为所选对象不返回 true在测试 equals()对于任何可用的项目。

#{country} 起,我还将对命名进行一些更改。是一个令人困惑的托管 bean 名称,因为它显然不代表 Country 的实例。类(class)。我叫它Data它应该保存应用程序范围的数据。

@ManagedBean
@ApplicaitionScoped
public class Data {

private static final List<Country> COUNTRIES = populateItSomehow();

public List<Country> getCountries() {
return COUNTRIES;
}

// ...
}

我假设 Country类有两个属性 codename .我假设接收所选国家/地区的托管 bean 具有 private Country country属性(property)。在您的 <f:selectItems> ,你需要循环 #{data.countries}并将国家对象指定为项目值,将国家名称指定为项目标签。

<h:selectOneMenu value="#{bean.country}">
<f:selectItems value="#{data.countries}" var="country" itemValue="#{country}" itemLabel="#{country.name}" />
</h:selectOneMenu>

现在,您需要创建一个 Converter对于 Country类(class)。我们将根据每个国家/地区唯一的国家/地区代码进行转换(对吗?)。在 getAsString()您实现将 Java 对象转换为其唯一的字符串表示形式的代码,该表示形式将在 HTML 中使用。在 getAsObject()您实现将唯一的 HTML 字符串表示形式转换回 Java 对象的代码。
@FacesConverter(forClass=Country.class)
public class CountryConverter implements Converter {

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return (value instanceof Country) ? ((Country) value).getCode() : null;
}

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return null;
}

Data data = context.getApplication().evaluateExpressionGet(context, "#{data}", Data.class);

for (Country country : data.getCountries()) {
if (country.getCode().equals(value)) {
return country;
}
}

throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Country", value)));
}

}
@FacesConverter将在 JSF 中自动注册它,并且 JSF 将在遇到 Country 的值表达式时自动使用它。类型。最终,您最终将国家代码作为项目值,将国家名称作为项目标签。 JSF 会将提交的国家/地区代码转换回完整的 Country表单提交时的对象。

在 JSF 1.x 中,原理并没有太大的不同。在此博客中,您可以找到两个基本的启动示例: Objects in h:selectOneMenu .

关于jsf - F :selectItems showing the class not a value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7353171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com