Dr. Winston Prakash Ph.D. 

Personal Website

Forward vs Redirect dispatching in a JSF application

One of the problems with JSF web application is proper handling of relative URLs. To solve these problems it is necessary to understand the JSF Controller Servlet request dispatch mechanism. While navigating to another page, the JSF Controller Servlet can either do a forward or a redirect dispatching. By default, the dispatch mechanism is forward (This has advantages which I'll cover later, may be in another blog).

Forward Dispatching

getServletContext().getRequestDispatcher().forward("second page");

The request forwarding is done internally by the JSF Controller Servlet to another resource. The browser is unaware of what has happened in the server side at the web container. So it still thinks it is tending to the original request and displays the original URL in its address bar. However, the page content displayed is from the second page.

Redirect Dispatching

response.sendRedirect("second page");

In this case, the JSF Controller Servlet instructs the client browser (via HTTP response header) to fetch another URL. So the browser fetches entirely a new URL and displays the second URL in its address bar. This could cause slight performance delay

Relative URL problems

Some of the complaints I heard are, when navigating to the another page, browser was not displaying the second page using the stylesheet set in that page or second page does not display the images.

Note, in the above scenario, user has placed the web page inside a subfolder (ex: folder1/page2.jsp) and the CSS file and images in a relative resource directory inside the sub folder (ex: folder1/resources/stylesheet.css). The CSS was linked relatively in the Page2.jsp as

 Ex. <link href="resources/stylesheet.css" type="text/css">

The above will not work in the case of forward dispatching (which is the default). Because, as explained above, after navigating to the second page, the browser is still tending the original request (even though the content displayed is of second page). So while fetching the stylesheet for the second page, browser will try to fetch it relative to the original URL.

There are two ways to solve this.

- Tell the JSF Controller to do a explicit redirect dispatching. To do this you need to manually edit the navigation.xml in the Creator generated web application (use Source tab in the Navigation Editor) and add </redirect> to the navigation rule

<navigation-rule>
   <from-view-id>/Page1.jsp</from-view-id>
   <navigation-case>
      <from-outcome>case1</from-outcome>
      <to-view-id>/folder1/Page2.jsp</to-view-id>
      </redirect>    </navigation-case> </navigation-rule>

- Use context relative path for the CSS files and images in the subfolder (Final version of Creator 2 will do the correct thing if user sets CSS or images via property sheet)

Ex. <link href="/folder1/resources/stylesheet.css" type="text/css">