Lester
Lester

Reputation: 1870

Primefaces commandButton calls action method on page refresh

Completely edited: Maybe I was mixing problems and misinterpreted. After simplifying my code the question simplifies to: How can I prevent the <p:commandButton> from executing it's action method on page refresh (like when you hit F5 inside browser window)?

JSF Code:

   <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:p="http://primefaces.org/ui">
    <h:body>
        <h:form>
            <h:outputText value="#{bugBean.number}" />
            <h:outputText value="#{bugBean.isComplete()}" />
            <p:commandButton id="entryCommand" value="add"
                action="#{bugBean.increase()}" update="@form" oncomplete="#{bugBean.complete()}"/>
        </h:form>
    </h:body>
    </html> 

backing bean code:

  package huhu.main.managebean;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class BugBean implements Serializable {

   private static final long serialVersionUID = 1L;
   private int number;
   private boolean isComplete = false;

   public void increase(){
      number++;
   }

   public void complete(){
      isComplete = true;
   }

   public int getNumber() {
      return number;
   }

   public void setNumber(int number) {
      this.number = number;
   }

   public boolean isComplete() {
      return isComplete;
   }

   public void setComplete(boolean isComplete) {
      this.isComplete = isComplete;
   }
}

Update: Even if I remove the oncomplete stuff like this an click the <p:commandButton> just once, the counter goes up on every page refresh.

<h:form>
        <h:outputText value="#{bugBean.number}" />
        <p:commandButton id="entryCommand" value="add"
            action="#{bugBean.increase()}" update="@form"/>
    </h:form>

Upvotes: 1

Views: 20440

Answers (2)

Lester
Lester

Reputation: 1870

The construct was lacking Ajax-support due to a missing head definition as it seems. In this case I just added <h:head/> right above the <h:body>-tag and everything worked fine.

Thanks to all contributors!

Upvotes: 5

perissf
perissf

Reputation: 16273

I think that the action method increase() is not called on each page refresh, but it's called the complete() method instead, and this is probably making you think that the action method has been called.

The oncomplete attribute inside the p:commandButton indicates a client side action, and so a JS method, and not a server action: the EL executes #{bugBean.complete()} when parses it on each page refresh.

Upvotes: 0

Related Questions