JSF/PrimeFaces selectOneMenu change view-id

前端 未结 3 986
萌比男神i
萌比男神i 2021-02-03 16:05

I\'m using JSF2 and PrimeFaces3. How can I write selectOneMenu that would invoke JSF navigation to redirect user to another page when he change option in menu?

相关标签:
3条回答
  • 2021-02-03 16:26

    Attach an ajax listener and let it navigate by NavigationHandler.

    E.g.

    <h:form>
        <h:selectOneMenu value="#{navigator.outcome}">
            <f:selectItem itemLabel="Select page..." />
            <f:selectItem itemValue="page1" itemLabel="Page 1" />
            <f:selectItem itemValue="page2" itemLabel="Page 2" />
            <f:selectItem itemValue="page3" itemLabel="Page 3" />
            <f:ajax listener="#{navigator.navigate}" />
        </h:selectOneMenu>
    </h:form>
    

    (the above example expects page1.xhtml, page2.xhtml and page3.xhtml in the same context; you can even make it a <f:selectItems> instead)

    with

    private String outcome;
    
    public void navigate() {
        FacesContext context = FacesContext.getCurrentInstance();
        NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
        navigationHandler.handleNavigation(context, null, outcome + "?faces-redirect=true");
    }
    

    The ?faces-redirect=true is not necessary, but it effectively sends a redirect so that the URL in browser address bar will properly change which is better for user experience and bookmarkability of the pages.

    0 讨论(0)
  • 2021-02-03 16:31

    You could have something like:

    <p:selectOneMenu value="#{myBean.mySelectedPage}">
               <f:selectItem itemValue="http://www.yahoo.com" itemLabel="yahoo"  />
               <f:selectItem itemValue="http://www.google.com" itemLabel="google" />
               <f:selectItem itemValue="search.jsf" itemLabel="search" />
               <p:ajax event="change" listener="#{myBean.myNavigationMethod}" />
     </p:selectOneMenu>
    

    and on your navigationMethod you have:

    String myPage = mySelectedPage
    FacesContext.getCurrentInstance().getExternalContext().redirect(myPage);
    

    The first two selectItem are for a full url and the last one is for another page in your web application(be careful that the extension must be the one set in your web.xml - it could be .jsf, .xhtml, .htm etc)

    0 讨论(0)
  • 2021-02-03 16:34

    Instead of using ajax navigation use the following:

    <p:selectOneMenu value="#{navigator.outcome}" onchange="window.location =this.options[this.selectedIndex].value">                      
        <f:selectItem itemLabel="Select page..." />
        <f:selectItem itemValue="page1" itemLabel="Page 1" />
        <f:selectItem itemValue="page2" itemLabel="Page 2" />
        <f:selectItem itemValue="page3" itemLabel="Page 3" />
        <p:ajax event="change" listener="#{navigator.navigate}" />
    </p:selectOneMenu>
    

    This works even if the session times out.

    0 讨论(0)
提交回复
热议问题