jsf-2.2java-ee-7

How to invoke a form action only when clicking the submit button


When sending a jsf request without any query parameters to the page with the following jsf code:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
    <head>
        <title>Search for Word</title>
    </head>
    <body>
        <div>
            <form method="get" action="#{dictionary.search()}" id="search">
                <input jsf:id="keyword" value="#{dictionary.keyword}" />
            </form>
            <button type="submit" form="search" value="Submit">Submit</button>
        </div>
    </body>
</html>

the action dictionary.search() is always invoked even without clicking the submit button. However, the action is not expected to be invoked until the submit button is clicked.

Question: How to change the jsf code without any other extra tag libraries but only the provided jsf tab lib, i.e. the pass-through element so that the managed bean method dictionary.method() is invoked only when the submit button is clicked?


Solution

  • I eventually found the answer myself:

                <form jsf:id="form">
                    <input type="text" jsf:value="#{dictionary.keyword}" />
                    <button jsf:action="#{dictionary.search}">Search</button>
                </form>
    

    The nitty-gritty here is the generation of the equivalent component tree of that generated by h:commandButton

    Based on the jsf 2.2 tutorial 8.5 HTML5-Friendly Markup,

    To make an element that is not a JavaServer Faces element a pass-through element, specify at least one of its attributes using the http://xmlns.jcp.org/jsf namespace

    the whole form has to passed through to jsf as a jsf component, the <form> element has to be like this <form jsf:id="form">, where the value of the id actually could be at random

    The same goes with both the <input> and <button> element and, as to the <input> element the type attribute has to be assigned with a value, here is text