Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

jsf 2 - JSF form post with AJAX

I want the following form to use AJAX. So the comments are shown after clicking the command button and without reloading the page. What needs to be changed, using Java Server Faces 2.0?

Functionality: This form provides an inputText to define a topic. After pressing the commandButton, it is searched for comments regarding this topic. Comments are shown in a dataTable, if there are any. Otherwise Empty is shown.

<h:form id="myForm">
    <h:outputLabel value="Topic:" for="topic" />
    <h:inputText id="topic" value="#{commentManager.topic}" />
    <h:commandButton value="read" action="#{commentManager.findByTopic}" />
    <h:panelGroup rendered="#{empty commentManager.comments}">
        <h:outputText value="Empty" />
    </h:panelGroup>
    <h:dataTable
        id="comments"
        value="#{commentManager.comments}"
        var="comment"
        rendered="#{not empty commentManager.comments}"
    >
        <h:column>
            <h:outputText value="#{comment.content}"/>
        </h:column>
    </h:dataTable>
</h:form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to tell the command button to use Ajax instead. It's as simple as nesting a <f:ajax> tag inside it. You need to instruct it to submit the whole form by execute="@form" and to render the element with ID comments by render="comments".

<h:commandButton value="read" action="#{commentManager.findByTopic}">
    <f:ajax execute="@form" render="comments" />
</h:commandButton>

Don't forget to ensure that you've a <h:head> instead of a <head> in the master template so that the necessary JSF ajax JavaScripts will be auto-included.

<h:head>
    ...
</h:head>

Also, the element with ID comments needs to be already rendered to the client side by JSF in order to be able to be updated (re-rendered) by JavaScript/Ajax again. So best is to put the <h:dataTable> in a <h:panelGroup> with that ID.

<h:panelGroup id="comments">
    <h:dataTable rendered="#{not empty commentManager.comments}">
        ...
    </h:dataTable>
</h:panelGroup>

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...