Below I have 2 buttons "Get Players In Same View", one is JSF button, non-ajax and the other is primefaces button with AJAX update. The backend bean "playersBean" is view scope. Both the buttons call method newPlayer which adds a string value to players list.
When I call the JSF button, the method works fine and the datatable list is updated and then after I reload the page like by using f5 key, playersBean is not reinitialized but the newPlayer method gets called.
When I call the primefaces button, the AJAX works fine and the list is updated. Now after that, when I reload the page, the playersBean is initialized again. How can I prevent from initializing the bean on every reload if i use AJAX update? How can I avoid method call on reload and if i use JSF non ajax button ?
index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h:form>
Just generated:
<h:outputText value="#{playersBean.player}"/><br/>
List of generated players:
<h:dataTable id="dt" var="t" value="#{playersBean.players}">
<h:column>
<h:outputText value="#{t}"/>
</h:column>
</h:dataTable>
<h:commandButton value="Get Players In Same View"
actionListener="#{playersBean.newPlayer()}"/>
<p:commandButton value="Get Players In Same View" update="dt"
action="#{playersBean.newPlayer()}"/>
</h:form>
</h:body>
</html>
PlayersBean.java
@ManagedBean
@ViewScoped
public class PlayersBean implements Serializable {
final String[] players_list = {"Nadal, Rafael (ESP)", "Djokovic,Novak (SRB)", "Ferrer, David (ESP)", "Murray, Andy (GBR)", "Del Potro, Juan Martin (ARG)"};
private ArrayList players = new ArrayList();
private String player;
public PlayersBean() {
ExternalContext extCon = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) extCon.getSession(false);
System.out.println("session: " + session);
System.out.println("Contructor PlayersBean");
}
//getters and setters
public void newPlayer() {
int nr = new Random().nextInt(4);
player = players_list[nr];
players.add(player);
System.out.println("players: " + players.size());
}
}