HTML Page Template Using JSP Tag

Apart from simple attribute, JSP also provides fragment tag feature. This can be used to create HTML page template.

Below is an example /WEB-INF/tags/page-template.tag file with two fragment attributes declared: header and content.

<%@ attribute name="header" fragment="true" %>
<%@ attribute name="content" fragment="true" %>
<!DOCTYPE html>

<html>
  <head>
    <!-- Place Common CSS here -->
    <!-- Common JS here -->
    <jsp:invoke fragment="header"/>
  </head>

  <body>
    <jsp:invoke fragment="content"/>
  </body>
</html>

Now you DRY yourself by reusing this template on your JSP pages. Below is a sample home.jsp:

<%@ taglib tagdir="/WEB-INF/tags" prefix="mycoolsite" %>
<mycoolsite:page-template>
  <jsp:attribute name="header">
    <!-- Page specific JS / CSS goes here -->
  </jsp:attribute>
  <jsp:attribute name="content">
    <h1>Hello World</h1>
  </jsp:attribute>
</mycoolsite:page-template>

Read more about JSP custom tag on the Official Java EE Tutorial.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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