JSF richfaces 自动完成功能不起作用

JSF richfaces autocomplete not working

我正在使用 richfaces 来获得自动完成功能,但它不起作用。我在这里研究了 richfaces 展示和 QA,但我无法让它工作。我在控制台上没有收到任何错误消息,Horse 列表不为空,已加载带有 AutocompleteBase.js 的 richfaces,

我的 xhtml:

...
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
...
<h:form>
   <rich:autocomplete mode="cachedAjax" minChars="1" 
         autocomopleteMethod="#{autoCompleteBean.autocomplete}"/>           
</h:form>
...

我的自动完成 Bean:

@Named
@RequestScoped
public class AutoCompleteBean {

private List<String> autocompleteList;
private List<Horse> horses;

    @PostConstruct
    private void init() {
        autocompleteList = new ArrayList<String>();
        for (Hors horse : horses) {
            autocompleteList.add(horse.getName());
        }
    }

    public List<String> autocomplete(String prefix) {
        ArrayList<String> result = new ArrayList<>();
        for (Iterator<Horse> it = autocompleteList.iterator(); it.hasNext();) {
            if (it.next().getName().startsWith(prefix)) {
                result.add(it.next());
            }   
        }
        return result;
    }
}  

HTML output img

您在一次迭代中调用了两次 it.next(),每次调用该方法时您都会获得不同的元素。

应该是autocompleteMethod而不是autocom**o**pleteMethod,所以:

<h:form>
    <rich:autocomplete mode="cachedAjax" minChars="1"
        autocompleteMethod="#{autoCompleteBean.autocomplete}" />
</h:form>

此外,检查 JSF2.0 中 @Named@ManagedBean 注释之间的区别 here

全部修改代码:

@ManagedBean // instead of @Named
@RequestScoped
public class AutoCompleteBean {

    // sample initialization, ensure that the list has some values
    @ManagedProperty(value = "#{someOtherBean.myHorses}")
    private List<Horse> horses;
    private List<String> autocompleteList;

    public List<String> autocomplete(String prefix) {
        ArrayList<String> result = new ArrayList<>();

        // don't use iterators unless you really need it
        // also, you had errors in this part (it.next)
        for (String s : autocompleteList) {
            if (s.startsWith(prefix)) {
                result.add(s);
            }
        }
        return result;
    }

    @PostConstruct
    public void init() {
        for (Horse horse : horses) {
            autocompleteList.add(horse.getName());
        }
    }

    public void setHorses(List<Horse> horses) {
        this.horses = horses;
    }
}

如果您使用 faces-config.xml 而不是注释,那么它应该是:

<managed-bean>
    <managed-bean-name>autoCompleteBean</managed-bean-name>
    <managed-bean-class>sample.package.AutoCompleteBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>horses</property-name>
        <value>#{someOtherBean.myHorses}</value>
    </managed-property>
</managed-bean>