JSF2 preRenderComponent is called whenever f: ajax is executed

I have a JSF page supported by NewsBean.java that has <f:event type="preRenderComponent" listener="#{newsBean.init}" /> as a bean initializer.

At the bottom of the page there is a button for sending comments, which has: <f:ajax event="click" execute="@form" render="@form" listener="#{newsBean.sendComment}" /> and is surrounded by <h:form> . When a button is pressed, NewsBean.init() is always called.

My bean area is the view. Is this a valid behavior (always calls init ())? How can I always prevent init() from being called?

+4
source share
2 answers

A preRender listener is always called in the pre render event, whether it is an initial request or a postback request. Each individual request has a rendering response stage, regardless of whether it is a regular request or an ajax request. Therefore, this behavior is determined by the specification. You need to check yourself in the listener method if it is a reverse request or not by checking FacesContext#isPostback() .

 public void sendComment() { if (!FacesContext.getCurrentInstance().isPostback()) { // ... } } 

<f:event type="preRenderXxx"> (where Xxx can be View or Component ), in fact, is a "workaround" to the functional requirement that the bean action method can be called after the viewing parameters are processed upon initial request. In the upcoming JSF 2.2, a new <f:viewAction> tag will be introduced, which should perform the task as intentional:

 <f:viewAction action="#{newsBean.sendComment}" /> 

This tag supports the onPostback attribute, which defaults to false :

 <f:viewAction action="#{newsBean.sendComment}" onPostback="false" /> 

JSF 2.2 will be released in the first quarter of 2012. JSF 2.2 snapshot releases are now available.

+9
source

I think your <f:event> tag fits inside the <h:form> . Therefore, when you click the ajax button, it re-displays the entire <h:form> component, which causes the preRenderComponent event to fire again.

I think you should use PreRenderViewEvent .

0
source

Source: https://habr.com/ru/post/1387002/


All Articles