Reputation: 1221
I have a JSF 1.2 / Seam 2.2.2 application. I have button and on click of the button, I run validations on the objects in current page, query for some dependent objects and run validation. If the validation passes, then I need to redirect the user to the new page. Otherwise, I need to display validation errors in the same page. Below code works fine and error message is displayed. But how to I redirect to a new page?
<h:messages id="errorMsg" errorClass="errorMessages" />
<a4j:commandButton action="#{myController.shouldRedirectToNewPage()}"
value="Button" styleClass="button" />
public void shouldRedirectToNewPage() {
//Run validation on objects in the current page
//Query for dependent objects and run validation
if(validationFails) {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"ERROR MESSAGE", null));
return;
}
}
Upvotes: 0
Views: 1165
Reputation: 1108802
Either use ExternalContext#redirect()
:
public void shouldRedirectToNewPage() throws IOException {
// ...
if (validationFails) {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR MESSAGE", null));
} else {
facesContext.getExternalContext().redirect("otherpage.jsf");
}
}
or return a navigation case string the usual way:
public String shouldRedirectToNewPage() {
// ...
if (validationFails) {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR MESSAGE", null));
return null;
} else {
return "otherpage";
}
}
with the following in faces-config.xml
:
<navigation-case>
<from-outcome>otherpage</from-outcome>
<to-view-id>/otherpage.jsf</to-view-id>
<redirect/>
</navigation-case>
(note the <redirect/>
, this makes it a redirect instead of a (default) forward)
Unrelated to the concrete problem, doing validation inside the action method isn't necessarily the best practice. It should be done by a Validator
. If it throws a ValidatorException
, then the action method simply won't be invoked.
Upvotes: 3