首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSF2搜索框

JSF2搜索框
EN

Stack Overflow用户
提问于 2011-09-25 15:59:22
回答 1查看 14.9K关注 0票数 2

我用javaee6和jsf2开发了一个小应用。我想要一个没有按钮的搜索字段(只需键入并按回车键,然后给出结果)。我在bean中有一个搜索方法:

代码语言:javascript
复制
public Book searchByTitle(String title) {
    this.book = bookFacade.searchByTitle(title);
    return book;
}

我想通过jsf页面调用这个方法(带参数?这是可能的吗?),所以我尝试这样做:

代码语言:javascript
复制
    <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函数。

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-25 16:16:03

在jsf页面中使用以下代码:

代码语言:javascript
复制
<h:form>
    <h:inputText id="search" value="#{bookBean.searchString}"></h:inputText>
    <h:commandButton value="Search by title" action="#{bookBean.searchByTitle(bookBean.searchString)}">
        <f:ajax execute="search" render="output"></f:ajax>
    </h:commandButton>
    <h2><h:outputText id="output" value="#{bookBean.book.title}"></h:outputText>
    </h2>
</h:form>

和你的java代码:

代码语言:javascript
复制
// note the return type is String. return type of methods which are to be called from actions of commandlinks or commandbuttons should be string
public String searchByTitle(String title)
{
    this.book = bookFacade.searchByTitle(title);
    return null;
}

编辑:

首先是就从jsf页面传递的参数而言,只有当您想要将一个bean的属性传递给另一个bean时,才应该使用它。在您的示例中,它不是必需的,因为您要设置相同bean的属性(SearchString),并将其传递给完全相同的bean。

你的第二个问题:你想让搜索在没有搜索按钮的情况下工作:你可以通过在h:inputText中添加一个valueChangeListener来实现。并将f:ajaxevent属性设置为blur

代码语言:javascript
复制
<h:form>
    <h:inputText id="search" value="#{bookBean.searchString}" valueChangeListener="#{bookBean.searchStringChanged}">
        <f:ajax execute="search" render="output" event="blur" />
    </h:inputText>
    <h2><h:outputText id="output" value="#{bookBean.book.title}" />
    </h2>
</h:form>

还要定义bookBean java代码的valueChangeListener方法:

代码语言:javascript
复制
public void searchStringValueChanged(ValueChangeEvent vce)
{
    searchByTitle((String) vce.getNewValue);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7544335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档