在 h:commandLink 中显示参数值

Display param value in h:commandLink

这里是 Home.xhtml 中的 commandLink:

<h:commandLink action="#{booksBean.selectBook()}">
    <h:graphicImage library="images/books" name="s1.jpg"/>
    <f:param name="isbn" value="25413652" />
</h:commandLink>

但是当我想点击它的时候,浏览器地址栏是:

http://localhost:8080/OBS2/Home.xhtml

如何在地址的和处添加 isbn 值 (25413652),并在下一页检索它(jsfbean)。

当我使用 h:outputLink 时,一切都很好,但是由于 h:outputLink 没有 action() 方法,我无法调用 bean 的 selectBook()

换句话说,您想要一个 GET link 而不是 POST link?在源页面中使用 <h:link> 而不是 <h:commandLink>,并在目标页面中使用 <f:viewParam> 来根据请求参数设置一个 bean 属性,如果需要的话连同一个 Converter 将表示 ISBN 编号的 String 转换为具体的 Book 实例。

例如在 Home.xhtml

<h:link outcome="Books.xhtml">
    <h:graphicImage name="images/books/s1.jpg" />
    <f:param name="isbn" value="25413652" />
</h:link>

并在 Books.xhtml

<f:metadata>
    <f:viewParam name="isbn" value="#{booksBean.book}" converter="isbnToBookConverter" />
</f:metadata>

使用此转换器

@FacesConverter("isbnToBookConverter")
public class IsbnToBookConverter {

    @Override
    public Object getAsString(FacesContext context, UIComponent component, Object modelValue) {
        Book book = (Book) modelValue;
        return (book != null) ? book.getIsbn() : "";
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null; // Let required="true" or @NotNull handle this condition.
        }

        String isbn = submittedValue;
        Book book = someBookService.getByIsbn(isbn);
        return book;
    }

}

感谢转换器,您无需任何操作即可设置所选图书。如果您需要根据设置书执行其他操作,只需将 <f:viewAction> 添加到 <f:metadata>.

<f:metadata>
    <f:viewParam name="isbn" value="#{booksBean.book}" converter="isbnToBookConverter" />
    <f:viewAction action="#{booksBean.initializeBasedOnSelectedBook}" />
</f:metadata>

另请参阅:

  • Creating master-detail pages for entities, how to link them and which bean scope to choose
  • What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
  • When should I use h:outputLink instead of h:commandLink?
  • How to navigate in JSF? How to make URL reflect current page (and not previous one)

与具体问题无关,注意我还修复了图像组件的library属性的不当使用。为了正确使用,请前往 What is the JSF resource library for and how should it be used? 并且,您最好将 XHTML 文件名小写,因为 URL 区分大小写,当用户尝试从中键入 URL 时,这将失败头顶并且不希望使用大写字母(==因此对用户体验不利)。