Passing “get” parameters doesn't work, paramet

2019-07-23 18:04发布

I'm a beginner to JSF and I want to code a little searchbar on my future website.

I made two pages : index.xhtml and search.xhtml, and I try to pass get parameters from index.xhtml to search.xhtml, so I made this little formular :

    <!-- index.xhtml -->
    <h:form id="Form_search">
        <h:inputText class="search_bar_text" binding="#{se}"></h:inputText>
        <h:button class="search_bar_button" outcome="search">
            <f:param name="search" value="#{se.value}" />
        </h:button>
    </h:form>

To summarize, I want to send the content of an inputText to search.xhtml

But there's a problem : when I click on the submit button, no parameters are passed, so instead of having /search.xhtml?search=foobar I only have /search.xhtml.

I also tried this, but this doesn't work either :

    <!-- index.xhtml -->
    <h:form id="Form_search">
        <h:inputText class="search_bar_text" binding="#{se}"></h:inputText>
        <h:button class="search_bar_button" outcome="search.xhtml?search=#{se.value}">
        </h:button>
    </h:form>

Can someone explain to me the reason of this problem and how I can fix it?

标签: jsf get
1条回答
祖国的老花朵
2楼-- · 2019-07-23 18:39

The <f:param value> and <h:button outcome> are evaluated during rendering the HTML output, not during "submitting" of the form as you seem to expect. Do note that there's actually no means of a form submit here. If you're capable of reading HTML code, you should see it in the JSF-generated HTML output which you can see via rightclick, View Source in webbrowser.

Fix it to be a true GET form. You don't need a <h:form>, <h:inputText>, nor <h:button> here at all. You don't want a POST form. You don't seem to want to bind the input to a bean property. You don't want a plain navigation button.

<form id="form_search" action="search.xhtml">
    <input name="search" class="search_bar_text" />
    <input type="submit" class="search_bar_button" />
</form>

Yes, you can just use plain HTML in JSF.

If you really, really need to use JSF components for this purpose for some reason, then you could also use this POST-redirect-GET-with-view-params trick.

First add this to both index.xhtml and search.xhtml:

<f:metadata>
    <f:viewParam name="search" value="#{bean.search}" />
</f:metadata>

Then use this form:

<h:form id="form_search">
    <h:inputText value="#{bean.search}" styleClass="search_bar_text" />
    <h:commandButton styleClass="search_bar_button" action="search?faces-redirect=true&amp;includeViewParams=true" />
</h:form>

This would perhaps make sense if you intend to use JSF validation on it. But even then, this doesn't prevent endusers from manually opening the URL with invalid params. You'd then better add validation to <f:viewParam> itself on search.xhtml.

See also:

查看更多
登录 后发表回答