我用javaee6和jsf2开发了一个小应用程序。我想要一个没有按钮的搜索字段(只需键入并按 Enter 键并给出结果)。 我在 bean 中有一个搜索方法:
public Book searchByTitle(String title) {
this.book = bookFacade.searchByTitle(title);
return book;
}
我想通过jsf页面调用这个方法(带参数?可以吗?),所以我尝试这样做:
<h:form>
<h:inputText id="search" value="#{bookBean.searchString}"></h:inputText>
<h:commandButton value="Search by title" action="#{bookBean.searchByTitle}">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
<h2><h:outputText id="output" value="#{bookBean.book.title}"></h:outputText>
</h2>
</h:form>
但这行不通。 在 jsf2 xhtml 页面中执行搜索字段的正确方法是什么?
编辑:我尝试使用/不使用参数调用 searchByTitle 函数。
提前致谢!
最佳答案
第一步,如果您使用 Java EE 6 兼容容器(例如 GlassFish V3、Resin 4、JBoss AS 6 或 7 等)并且您已将 commons-el.jar 之类的内容放入 WEB-INF,<强>删除它。这是没有必要的,而且只会造成伤害。
I want a search field with no button (just type and hit enter and give the result)
在这种情况下,您也不需要命令按钮,但可以使用如下所示的按钮:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head/>
<h:body>
<h:form>
<h:inputText id="search" value="#{bookBean.searchString}"
onkeypress="if (event.keyCode == 13) {onchange(event); return false;}"
onchange="return event.keyCode !== undefined"
>
<f:ajax listener="#{bookBean.updateBook}" render="output" />
</h:inputText>
<h2>
<h:outputText id="output" value="#{bookBean.book}"/>
</h2>
</h:form>
</h:body>
</html>
将 bookBean
定义为:
@ViewScoped
@ManagedBean
public class BookBean {
private Map<String, String> exampleData = new HashMap<String, String>() {{
put("dune", "The Dune Book");
put("lotr", "The Lord of the Rings Book");
}};
private String searchString;
private String book;
public void updateBook(AjaxBehaviorEvent event) {
book = exampleData.get(searchString);
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getBook() {
return book;
}
}
在 Facelet 中,请注意 h:head
元素的重要性。如果没有它,JSF 就不知道在响应中的何处插入 AJAX 支持所需的脚本。
在示例中,当 f:ajax
客户端行为添加到所谓的 EditableValueHolder
时,JSF 生成的默认 onchange
方法每当用户按下回车键时就会被调用。监听器属性会导致在 AJAX 事件上调用一个方法。由于 searchString
已绑定(bind)到支持 bean 的属性,因此您不必将其作为参数提供给监听器方法。
此方法的一个小缺点是,当您更改搜索字段中的值并只需在其外部单击时,AJAX 调用也会被调用。
更新
向 h:inputText
添加 onchange
处理程序修复了上述问题。 JSF 会自动将其与来自客户端行为的 AJAX 代码链接起来。如果返回 false,则链将中止,因此 AJAX 调用不会发生。
如果处理程序是由真正的更改事件触发的,则处理程序onchange="return event.keyCode !== undefined"
将返回 false ;事件对象将不具有 keyCode
属性。
关于jakarta-ee - JSF2 搜索框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7544335/