Revisiting the almighty DRY (Do not Repeat Yourself) principle of software programming, reusing HTML elements can be done via JSP tags. One obvious application is when including common css, javascript etc on your html header.
Firstly create a .tag file containing the reusable code. In here I created /WEB-INF/tags/myheader.tag
<%@ tag %>My Cool Website
And now I can use this anywhere else I need it. Just declare the tag prefix and location and place it
<%@ taglib prefix="wohoo" tagdir="/WEB-INF/tags" %>Hello world!
The tag can also be parametrized to inject it with different settings. Declare the attribute like this in the tag file:
<%@ tag %> <%@ attribute name="thetitle" %>${thetitle}
And the title attribute can be set on the including page
Of course, the tag can be nested too. Below code will produce the image of both campaignA and campaignB just by simply using
campaignA.tag
<%@ tag %>![]()
campaignB.tag
<%@ tag %>![]()
marketing.tag
<%@ tag %> <%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
login.jsp
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %> ...
Another useful application of JSP tag is when including javascript. Having multiple tags can slow down load time of your website as each of them require one HTTP request. If you use JSP tag instead, you can still separate the file but when it’s rendered to the browser it will appear as if the scripts were inline.
Using Fragment Attribute
Another neat trick is to use fragment attribute. Say you want to build a html template with customized body element:
template.tag
<%@ tag %> <%@ attribute name="header" fragment="true" %> <%@ attribute name="body" fragment="true" %>My Website
home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %> <%@ taglib tagdir="/WEB-INF/tags" prefix="mytag" %>Some body content goes here
Read more about JSP custom tags on Java EE 5 Tutorial.
How can I reference the body of my custom tag within the .tag file?
I’ve added additional section on the post about fragment attribute.