Question

When I click on a command button of <h:form> tag in the mentioned below page, I expect that query parameters are sent as request parameters once I hit the submit button, as my page URL is ../index.xhtml?cid=12&ctype=video.

I expected that in my action method it should be printed CID=12, however, it printed CID=NULL. What is the problem and how can I solve it?

My view:

<h:body id="body">
    <h:form id="form">    
        <p:commandButton action="#{authorizationBean.getParameters()}" value="Ajax Submit" id="ajax" />   
    </h:form> 
</h:body>

My managed bean:

@ManagedBean
@SessionScoped
public class AuthorizationBean {

    public boolean getParameters(){
        Map<String, String> parameterMap = (Map<String, String>) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequestParameterMap();
        String cid = parameterMap.get("cid");
        System.out.println("CID="+cid);
        return true;
    }

}
Was it helpful?

Solution

By default, your code (and especially your <h:form> tag) generates the following HTML output:

<form id="form" name="form" method="post" action="/yourApp/yourPage.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="submit" name="j..." value="Ajax Submit" />
    <input id="javax.faces.ViewState" ... />
</form>

Note that the action of the generated <form> element is the current view id without any get parameters attached to it, despite the initial page could have had them. Thus, they are not set on form submit as well.

To handle the situation you can:

  1. Use a @ViewScoped bean holding the values of those parameters upon initial access;
  2. Add some hidden input fields to your form so that they are sent upon form submit as well or nest <f:param> inside your <h:commandButton>;
  3. Use OmniFaces' <o:form includeViewParams="true"> tag (Tag documentation / Showcase example) instead of the <h:form>, as it will submit to the current URL with view parameters attached, provided they were set using <f:viewParam> (see, for example, BalusC's answer to Retain original GET request parameters across postbacks for details).

OTHER TIPS

This is how I do, i just can't tell you if it's the best way...

Client-Side:

<h:outputLink target="_blank" value="detalhepesquisa.jsf">
        <h:outputText value="#{te.empresa.nome}" />
        <f:param name="id" value="#{te.empresa.id}"></f:param>
</h:outputLink>

In your bean:

String parametroID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top