Java – ASP.NET Master Pages equivalent in Java

javamaster-pagesmodel-view-controller

What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages?

I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages.

Any examples would be great!!

Best Answer

You should also check out Facelets; there is a good introductory article on DeveloperWorks.

The Facelets <ui:insert/> tag is comparable to the ASP.NET <asp:ContentPlaceHolder/> tag used in master pages; it lets you provide default content for that area of the page, but this can be overridden.

To fill the Facelets template in another page, you start with a <ui:composition/> element that points to the template file. This is roughly equivalent to declaring the MasterPageFile attribute in an ASP.NET page.

Inside the <ui:composition/> element, you use <ui:define/> elements to override the template defaults, similar to the way an <asp:Content/> tag is used. These elements can contain any kind of content - from simple strings to JSF elements.

So, to bring it all together...

In master.xhtml:

<!-- HTML header content here -->
<ui:insert name="AreaOne">Default content for AreaOne</ui:insert>
<ui:insert name="AreaTwo">Default content for AreaTwo</ui:insert>
<!-- HTML footer content here -->

In page.xhtml:

<ui:composition template="/WEB-INF/templates/master.xhtml">
  <ui:define name="AreaOne">Here is some new content</ui:define>
  <ui:define name="AreaTwo">
    <p>Some new content here too</p>
  </ui:define>
</ui:composition>

And this will render as:

<!-- HTML header content here -->
Here is some new content
<p>Some new content here too</p>
<!-- HTML footer content here -->

You also get some other benefits with Facelets, such as the ability to reuse page components with different data.

(Edited to provide more information.)