简体   繁体   中英

Ajax update executes once though event occurs many times

I'm starting to learn Primefaces framework, based on JSF and AJAX and I'm having some trouble.

I was trying a simple example such as having an inputText and I was trying to set a counter that increments its value every time a key is pressed on the inputText . To do this I used AJAX and a Bean. The problem is that the counter only is increased the first time, after that it remains the same. Here's my code:

WEB PAGE

<!DOCTYPE html>
<html xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>AJAX LISTENER</title>
</h:head>
<h:body>
    <h:form>
        <h:inputText id="counter">
            <p:ajax update="out" event="keypress" listener="#{counterBean.increment}"/>
        </h:inputText>
        <br/>
        AJAX listener = <h:outputText id="out" value="#{counterBean.count}" />
    </h:form>
</h:body>
</html>

BEAN

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class counterBean {
    private int count;
    public counterBean() {
        this.count = 0;
    }
    public void increment(){
        this.count = this.count +5;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }
}

Refer to : http://www.primefaces.org/documentation

In your case the better event is keyup I don't think it has a keypress event in primefaces.

Section 8.3 in the user guide 4.0

  • Ok your answer is actually very simple, I did testing and after finally realising the stupidity of it all...

Your ManagedBean is only RequestScoped - thus it's getting re-initalised every request... Change it to @ViewScoped.

A great doco on beans is : http://balusc.blogspot.com.au/2011/09/communication-in-jsf-20.html#ManagedBeanScopes

该bean需要进行观察。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM