How to create master page in Java/JSP ?

UPDATED: 16 July 2011

Hello Java developer you face many problems regarding the developing site and you have to maintain design for all the page as a same. ASP .Net supports master page but what about JSP. I'll show you how you can create master page for your site.

The API that helps to create the master page is "SiteMesh" developed by Open Symphony. You want to check out the site click here . We'll discuss sitemesh 2 series. Yet not tested sitemesh 3.

Download JSTL :

Sitemesh is a java web application development framework developed by Open Symphony.

Some time website uses the same menu and other content to all pages. Example  like Menubar in head of the page it'll be used on every page ti navigate the site. Template(Master Page) comes here to apply certain design to every page of domain.

How it works?

Step 1: Create blank JSP page. Include taglib at the top. You can copy paste below code. This will be the master page.
<%@taglib uri="" prefix="decorator"%>
<%@taglib uri="" prefix="c" %>
<%@taglib uri="" prefix="fn" %>

Step 2: Sample code of master page.
<%@taglib uri="" prefix="decorator"%>
<%@taglib uri="" prefix="c" %>
<%@taglib uri="" prefix="fn" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Step 3: Configure the sitemesh to pass request of the page through the template/master page. Create decorators.xml file in WEB-INF folder as follow.
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/template">
    <decorator name="main" page="template1.jsp">
  • - defaultdir : Path of template/master page
  • - page : Template/master page that will be applied to pages
  • - /Folder_name/* : The URL pattern (Directory) on which the template/master page will be applied.if we use /* so all request pages pass through the template and it'll be applied to all page.   
  • - /Folder_name2/test.jsp : Template/master page will render only test.jsp file of Folder_name2 directory. Other file will be displayed as normal page.

Step 4: Configure the web.xml file. Append the below code in web.xml file.

  • - /* : Template applied to all page extension.
  • - /.html : Template applied to only on html page.