Creating Reusable HTML Using JSP Tag

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 %>
<title>My Cool Website</title>
<link rel="stylesheet" href="resources/common.css"/>
<script type="text/javascript" src="resources/common.js"><!-- --></script>

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" %>
<html>
  <head>
    <wohoo:myheader/>
  </head>
  <body>
    <h1>Hello world!</h1>
  </body>
</html>

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" %>
<title>${thetitle}</title>
<link rel="stylesheet" href="resources/common.css"/>
<script type="text/javascript" src="resources/common.js"><!-- --></script>

And the title attribute can be set on the including page

<wohoo:myheader thetitle="My Cool Website"/>

Of course, the tag can be nested too. Below code will produce the image of both campaignA and campaignB just by simply using <my:marketing/> tag.

campaignA.tag

<%@ tag %>
<img src="campaignA.jpg"/>

campaignB.tag

<%@ tag %>
<img src="campaignA.jpg"/>

marketing.tag

<%@ tag %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<my:campaignA/>
<my:campaignB/>

login.jsp

<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
...
<my:marketing/>

Another useful application of JSP tag is when including javascript. Having multiple <script src="myscript.js"> 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.

Read more about JSP custom tags on Java EE 5 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