1

This is my first question.

I am trying to increment a variable value in a textbox when a button is clicked using primefaces.

But through debug I found out that whenever I click the p:commandButton, EL bean function call, tries to increment the bean class variable "counter", whenever this happens the value of counter is always 0, so it gets incremented to 1 and that is shown in my webpage. It never reaches 2, 3, 4...

Below is the code:

xhtml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<h:head></h:head>

<h:body>
    <h:form>
        <h:panelGrid columns="2" cellpadding="5">
            <h:outputLabel value="Counter:"/>
            <h:outputText id="output" value="#{counterView.counter}" />

            <p:commandButton value="Count" action="#{counterView.increment}" update="output"  />
        </h:panelGrid>
    </h:form>
</h:body>
</html>

Java:

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;

@ManagedBean(name="counterView")
@ViewScoped
public class counterView implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 2369382392318418242L;
    private int counter = 0;

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public void increment() {
        // Counter is 0 always the moment this function is entered...
        this.counter = this.counter + 1;
    }
}

I cant figure out where I am going wrong as its a classical example in primefaces showcase and I am following that...

Thanks in advance

CodeLover
  • 13
  • 4

1 Answers1

2

You use the wrong ViewScoped annotation. You have to use the javax.faces.bean.* annotations in combination with @ManagedBean.

see: @SessionScoped bean looses scope and gets recreated all the time, fields become null

tandraschko
  • 2,291
  • 13
  • 13