JSF richfaces自动完成无法正常工作

时间:2016-06-08 22:24:35

标签: jsf jsf-2 autocomplete richfaces

我正在使用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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

另外,请检查JSF2.0 here@Named@ManagedBean注释之间的区别。

整个修改过的代码:

@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>