【发布时间】:2017-12-15 17:34:39
【问题描述】:
我有一个书籍列表,我尝试根据文本(标题)和类别过滤它们
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 变量为空,反之亦然
豆长这样
@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 在调用时考虑这两个变量?
【问题讨论】:
-
为了在重新提交时保留属性的先前值,您需要使用比请求范围更广的bean,在这种情况下至少是视图范围的bean。
-
你能给我一个关于如何完成的提示吗?
-
将托管 bean
BooksBean上方的@RequestScoped更改为@ViewScoped(仔细从 CDI 包中导入该注释,javax.faces.view.ViewScoped)。 -
这确实有效。非常感谢!