Bean中的变量没有通过按钮单击保持其值

时间:2018-12-06 12:16:38

标签: ajax web-applications primefaces

这是我的第一个问题。

当我使用质数单击按钮时,我试图在文本框中增加变量值。

但是通过调试,我发现每当单击EL bean函数调用p:commandButton时,都会尝试增加bean类变量“ counter”,每当这种情况发生时counter的值始终为0,因此它会递增为1,并显示在我的网页中。它永远不会达到2、3、4 ...

下面是代码:

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

我无法弄清楚哪里出了问题,因为它是primefaces展示柜中的经典示例,我一直在关注...

预先感谢

1 个答案:

答案 0 :(得分:2)

您使用了错误的ViewScoped批注。您必须将javax.faces.bean。*批注与@ManagedBean结合使用。

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

相关问题