Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
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" />
        rendered="#{not empty commentManager.comments}"
            <h:outputText value="#{comment.content}"/>
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" />

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.


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}">

See also:

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

547k answers


35.4k users