JSF index.xhtml and redirect to actions with faces

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

I am completely new to JSF (using JSF 2.0) and I need your advice. What are the best methods to redirect from an index page to an action in a controller?

///a 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); } } 
+4
source share
1 answer

You can use the JSF event preRenderView to redirect to another page as follows:

In the 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 a managed bean first way

  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 the second method

  public class yourClass{ public void methodInManagedBean() throws IOException { FacesContext.getCurrentInstance().getExternalContext().redirect("list.do");//add your URL here, instead of list.do } } 
+9
source

Source: https://habr.com/ru/post/1438842/


All Articles