I want to redirect from a link in a JSF page, how can I do it?
In HTML I can use <a>
tag for this. But in JSF I use <h:outputLink>
or <h:commandLink>
as they can be conditionally rendered. I want redirect link to other page in same application or to an external URL. How can I do it with JSF? How can I use action
in <h:commandLink>
for this?
To enable the page redirection in JSF 2.0, you can append “ faces-redirect=true ” at the end of the outcome string. Page forward. Page redirection. In the navigation rule, you can enable the page redirection by adding a <redirect /> element within the <navigation-case />.
The redirection facility is a JSF 2.0 feature, so jsf1.x doesn’t support like this navigation. 1. Managed Bean 2. The Views 3. Faces Configuration File 4. The Deployment Descriptor (web.xml) (=default). See JSF Specification 2.5.2 5. JSF 2 Redirection Demo
As you can see in the previous examples urls are not changed while navigating from one view page to another because JSF by default uses forward functionality instead of redirect. For page redirection we have to append faces-redirect=true at the end of the view name. When “Welcome” link is clicked welcome.xhtml page will display.
Page Forward Browser send a “ GET ” request to URL : http://localhost:8080/JavaServerFaces/faces/start.xhtml. JSF received the request and return the “ start.xhtml “. Browser display the content of “ start.xhtml “. User click on the button. JSF received the action and perform an internal page forward to “ page1.xhtml ” in the server side.
Assuming that you'd like to redirect to some.xhtml
which is placed in web root folder:
You can just continue using plain HTML.
<a href="#{request.contextPath}/some.xhtml">go to some page</a>
For conditional rendering, just wrap it in an <ui:fragment>
.
Or use <h:link>
with implicit navigation.
<h:link outcome="/some" value="go to some page" />
Note: no need to prepend context path nor to include FacesServlet
mapping.
Or use <h:commandLink>
with ?faces-redirect=true
.
<h:commandLink action="/some?faces-redirect=true" value="go to some page" />
Note: no need to prepend context path nor to include FacesServlet
mapping.
Or use <h:outputLink>
, but you need to specify context path.
<h:outputLink value="#{request.contextPath}/some.xhtml" value="go to some page" />
Redirecting to an external URL is already answered in this duplicate: Redirect to external URL in JSF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With