我有一份书籍清单,我尝试根据文字(标题)和类别过滤它们
index.xhtml
文件看起来像这样
<h:form>
<h:inputText a:placeholder="Search by title" value="#{booksBean.searchString}"
onkeypress="if (event.keyCode == 13) {onchange(event); return false;}"
onchange="return event.keyCode !== undefined">
<f:ajax listener="#{booksBean.updateBook}" render="output"/>
</h:inputText>
<h:panelGroup style = "margin-left: 5px;">
<h:form>
<h:selectOneMenu id="combo" value="#{booksBean.selectedCategory}">
<f:selectItems value="#{booksBean.categories}" var="category" itemValue="#{category}" />
<f:ajax listener="#{booksBean.updateBook}" render="output" />
</h:selectOneMenu>
</h:form>
</h:panelGroup>
</h:form>
<h:panelGroup id="output">
<h:form>
<ui:repeat value="#{booksBean.books}" var="book">
<ui:decorate template="/templates/product-summary.xhtml">
<ui:param name="book" value="#{book}"/>
<ui:define name="product-description">
<p>#{book.description}</p>
</ui:define>
</ui:decorate>
</ui:repeat>
</h:form>
</h:panelGroup>
设置searchString
后,selectedCategory
变量将变为空,反之亦然
Bean看起来像这样
@Named("booksBean") //name of the bean is booksBean
@RequestScoped
public class BooksBean {
private BookRepository bookRepository = new BookRepository();
public Set<String> getCategories() {
return categories;
}
public void setCategories(Set<String> categories) {
this.categories = categories;
}
private Set<String> categories = new LinkedHashSet<>();
private String searchString = "";
private List<Book> books;
public String getSelectedCategory() {
return selectedCategory;
}
public void setSelectedCategory(String selectedCategory) {
this.selectedCategory = selectedCategory;
}
private String selectedCategory = "";
@PostConstruct
public void initialize() {
books = bookRepository.getBooksByTitleAndCategory(searchString, selectedCategory);
getAllCategories();
}
public List<Book> getBooks() {
return books;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
private void getAllCategories() {
categories.add("");
for (Book book : bookRepository.findAll()) {
categories.add(book.getCategory_name());
}
}
public void updateBook(AjaxBehaviorEvent event) {
this.books = bookRepository.getBooksByTitleAndCategory(searchString, selectedCategory);
}
}
有什么方法可以让ajax在拨打电话时考虑这两个变量?
答案 0 :(得分:1)
正如Tiny建议的那样
&#34;将@RequestScoped
更改为托管bean BooksBean上方的@ViewScoped
(仔细地从CDI包中导入该注释,javax.faces.view.ViewScoped
)。&#34;