Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF index.xhtml and redirect to faces action

I think its a good practice to have an index page (in my case index.xhtml). I want to pass some action on index page (for example in struts:<c:redirect url="list.do" /> and I go to struts action class without any links and buttons) I know if I want to use navigation I should use commandLink-s or buttons). I can write <h:commandButton> with onclick javascript function, but I don't feel this is the best option.

I'm totally new to JSF (using JSF 2.0) and I need your advice. What are the best practices for redirecting from index page to an action in controller?

///new version

<!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:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<f:view>
<ui:insert name="metadata"/>
    <f:viewParam name="action" value="listItems.xtml"/>
    <f:event type="preRenderView" listener="#{yourBean.methodInManagedBean}" />
<h:body></h:body>
</f:view>
</html>

public class ForwardBean {

    private String action;

    // getter, setter

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = action; 
        facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
    }
}
like image 598
Ray Avatar asked Dec 21 '22 15:12

Ray


1 Answers

You can use JSF preRenderView event to redirect to another page in following manner,

In your index.xhtml file

<!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:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<f:view>
<ui:insert name="metadata"/>
    <f:event type="preRenderView" listener="#{yourBean.methodInManagedBean}" />
<h:body></h:body>
</f:view>
</html>

In managed bean, 1st way is

    public class yourClass{

    FacesContext fc = FacesContext.getCurrentInstance();
    ConfigurableNavigationHandler nav = (ConfigurableNavigationHandler)fc.getApplication().getNavigationHandler();

    public void methodInManagedBean() throws IOException {
        nav.performNavigation("list.do");//add your URL here, instead of list.do
    }
    }

or you can use 2nd way

    public class yourClass{ 

    public void methodInManagedBean() throws IOException {
         FacesContext.getCurrentInstance().getExternalContext().redirect("list.do");//add your URL here, instead of list.do
    }
    }
like image 167
Swarne27 Avatar answered Dec 23 '22 04:12

Swarne27