JSF redirect on page load

In JSF 2.0, you can use javax.faces.event.PreRenderViewEvent system event to perform custom logic before JSF page is displayed.

For eg : If user belongs to admin group you would like to redirect the user to Administration page and if its a normal user should be redirected to a different page.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221;
xmlns:h=”http://java.sun.com/jsf/html&#8221;
xmlns:f=”http://java.sun.com/jsf/core&#8221;
>

<f:event listener=”#{pageBean.isUserAdministrator}” type=”preRenderView” />

<h:body>

<h:outputText value=”Default Page ..” />

</h:body>

</html>


 

public void isUserAdministrator(ComponentSystemEvent event){
//If logged with admin ID
 if(userBean.getWpsadmin()!=null &amp;amp;amp;amp;&amp;amp;amp;amp; userBean.getWpsadmin().compareTo(Constants.WPSADMIN)==0)
 {
 //Redirect to admin page
 userBean.gotoPage(Constants.ADMINXHTML);
 }
else
{
//Redirect to normal page
}
 }
//Redirection ...
public void gotoPage(String pageName) {
 if (pageName != null) {
 FacesContext context = getFacesContext();
 UIViewRoot newView =
 context.getApplication().getViewHandler().createView(
 context,
 pageName);
 context.setViewRoot(newView);
 context.renderResponse();
 }
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s