Problem:h:commandButton ajax not working with JSF bean, while page is loading.
A have JSF page with long list (takes couple seconds to load):
<?xml version="1.0" encoding="UTF-8" ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:co="http://java.sun.com/jsf/composite/standart/components">
<h:form id="myForm">
<div><h:outputLabel value="My name is #{myViewBean.name}" /></div>
<h:commandButton
action="#{myViewBean.actRedirectToAnotherView()}"
value="Redirect"/>
<h:dataTable value="#{myViewBean.bigList}" var="entity">
<h:column>
#{entity}
</h:column>
</h:dataTable>
</h:form>
</html>
And managed view scoped bean “MyViewBean”:
package mypackage;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
@Named
@Scope(value = "view")
public class MyViewBean {
private static int beanNrCounter = 0;
private static final List<String> bigList = new ArrayList();
static {
for (int i = 0; i < 100000; i++) {
bigList.add("Item in big list " + i);
}
}
private final String name;
public MyViewBean() {
beanNrCounter++;
name = "BEAN NR " + beanNrCounter;
System.out.println("Created MyViewBean with name " + name);
}
public String actRedirectToAnotherView() {
String viewName = "anotherView.jsf";//actually some complex operation which decides where to redirect user
System.out.println("Redirecting to another view " + viewName );
return viewName + "&faces-redirect=true";
}
public String getName() {
return name;
}
public List<String> getBigList() {
return bigList;
}
}
If I click button "Redirect" while page is loading method “actRedirectToAnotherView” is not executed, but instead another “MyViewBean” bean is created. If I click button then page is already loaded, everything works as expected.
I have inspected, that then "Redirect" button is clicked, if page is loaded form parameter javax.faces.ViewState is passed with ajax post, but if page is loading - javax.faces.ViewState is missing (so off course new view is created).
If I change scope of managed bean to "request" problem stays ("Redirect" button is still not working, actRedirectToAnotherView is not executed).
How can I fix ajax behaviors while page is loading? It seems to me that javax.faces.ViewState is known on client side as soon as MyViewBean is accessed, so javax.faces.ViewState should be passed regardless if page is already loaded or not.
I am using:
- JSF Mojarra (2.2.6)
- Spring: “view scope” is done by example https://github.com/michail-nikolaev/primefaces-spring-scopes/blob/master/primefaces-scopes-test/src/main/java/org/nkey/primefaces/scopes/test/spring/scope/ViewScope.java
- Primefaces (5.1)