我的要求是在单击按钮时触发和ajax请求,并在页面刷新时显示验证错误。此外,如果没有错误,请导航到第二个视图。以下是我尝试的代码。我使用jsf 2.1.7与Jboss 7.1.1 final。
<h:form>
<h:inputText value="#{helloBean.name}"></h:inputText>
<h:commandButton value="Welcome Me" action="#{helloBean.goToWelcome}">
<f:ajax event="click" listener="#{helloBean.goToWelcome}"></f:ajax>
</h:commandButton>
</h:form>
HelloBean.java
@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {
public String goToWelcome(){
System.out.println("in goToWelcome");
return "welcome";
}
}
我在与xhtml相同的文件夹中有一个welcome.xhtml,我可以看到goToWelcome()方法也被触发,但导航不会发生。我假设它是因为根据规范监听器属性应该有一个带有void返回类型的方法,并且忽略来自goToWelcome()的返回字符串。那么有没有办法达到我的要求。任何形式的帮助将受到高度赞赏。谢谢。
答案 0 :(得分:0)
基本上,您需要从操作方法返回导航案例结果以进行导航。请注意,AJAX监听器无法进行导航,至少是直接导航。如果您不想执行导航,则可以从操作方法返回null
。此外,如果存在转换/验证错误,则不会进行导航,也不会调用您的操作方法。因此,您需要分配一堆<h:message>
或全局<h:messages>
来显示错误消息。
要合并它,以下内容足以实现您的功能。
观点:
<h:form>
<h:messages id="messages">
<h:inputText value="#{helloBean.name}" />
<h:commandButton value="Do AJAX validation and navigate if necessary" action="#{helloBean.goToWelcome}">
<f:ajax execute="@form" render="messages" />
</h:commandButton>
</h:form>
豆子:
@ManagedBean
@ViewScoped
public class HelloBean implements Serializable {
public String goToWelcome(){
//do business job
if(/* some condition met */) {
return null;
} else {
return "nextpage";
}
}
}
您主题的相关阅读
答案 1 :(得分:0)
您可能需要redirect
页面(假设您没有验证错误,它应该有效)
return "nextpage.jsf?faces-redirect=true";