Monday, July 20, 2009

DRY Views with Nested Templates in EasyWeb4J

The content of pages in any web application will be composed of three parts.
  1. The elements common across all pages (header, main navigation and footer).
  2. The elements common to specific group of pages (sidebar).
  3. The actual content of the page.
At first glance, it may appear that EasyWeb4J does not support nested layout components as there is only one layout file (Application.jsp). However, since it is a plain JSP page, you can do anything you do with plain old JSP pages in it.

This post, demonstrates how filters of EasyWeb4J can be used along with the EasyWeb4J's templating system to achieve nested layouts. There are two controllers (Products & Services) in this application each with their own sidebar links.

The completed application would look like this

Download the complete source code for this application.

The trick to create nested layout components, is using the filter to setup a request attribute, which will provide the nested layout page. This can then be used within Application.jsp to include the nested layout page. By using a filter you do not have to do this in each action within the controller. Thus both our controllers and views would be DRY.

Create a new EasyWeb4J Hibernate Project as described in the tutorial. Since we do not need a database for this demo, delete src/main/resources/repositories.properties from the newly created project.

The Master Layout

src/main/webapp/WEB-INF/layouts/Application.jsp

As it is seen here, the master layout specifies the header, main vaigation and the copyright notice. It then includes the sidebar specific to the controller and the actual view of the action invoked during the request.

The Sidebars

src/main/webapp/WEB-INF/layouts/ProductsBar.jsp

src/main/webapp/WEB-INF/layouts/ServicesBar.jsp

Filters in Controllers

src/main/java/org/layout/controllers/ProductsController.java

src/main/java/org/layout/controllers/ServicesController.java

The filters in the controllers setup the request attribute ("sidebar") with the appropriate page containing the sidebar for the actions of this controller. The filters may also provide different sidebars for groups of actions if needed, by determining which action has been invoked using the getActionInvoked() method.

If your application needs to have the view of the action within the nested layout page, move the include for ${view}, from Application.jsp to your nested layout page.

Template out as much of your views as possible and DRY them up.

0 comments:

Post a Comment