There are certain cases where you are needed to redirect to a different page than requested by user e.g. if user has requested a secure page for which he/she is not authorized, your application will have to redirect to login page or some other page. I have created a utility method to redirect to a page. You can call anywhere but for example given above, you can call it a beforePhase method of RestoreViewPhaseListener. Here is the method code:
viewId is the name of page to which it should redirect e.g. "/redirect.xml" (assuming page is at root level). Inside execute method, you get the ViewDeclarationLanguage which is page type specific e.g. if page is in facelet markup, you get DefaultFaceletViewDeclarationLanguage and if page is in JSP markup, then you will get corresponding ViewDeclarationLanguage. After this, page root tree is constructed by calling createMetadataView if it is not already constructed. Finally set the new ViewRoot and call renderResponse method, which will bypass all phases and will jump directly to render phase.
public static void redirect(String viewId) {
execute(FacesContext.getCurrentInstance(), viewId);
}
private static void execute(FacesContext facesContext, String viewId)
throws FacesException {
UIViewRoot viewRoot = null;
ViewDeclarationLanguage vdl = facesContext.getApplication()
.getViewHandler()
.getViewDeclarationLanguage(facesContext, viewId);
if (vdl != null) {
// If we have one, get the ViewMetadata...
ViewMetadata metadata = vdl.getViewMetadata(facesContext,
viewId);
if (metadata != null) { // perhaps it's not supported
// and use it to create the ViewRoot. This will have, at
// most
// the UIViewRoot and its metadata facet.
viewRoot = metadata.createMetadataView(facesContext);
}
}
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
assert (null != viewRoot);
}
viewId is the name of page to which it should redirect e.g. "/redirect.xml" (assuming page is at root level). Inside execute method, you get the ViewDeclarationLanguage which is page type specific e.g. if page is in facelet markup, you get DefaultFaceletViewDeclarationLanguage and if page is in JSP markup, then you will get corresponding ViewDeclarationLanguage. After this, page root tree is constructed by calling createMetadataView if it is not already constructed. Finally set the new ViewRoot and call renderResponse method, which will bypass all phases and will jump directly to render phase.