Custom JSP tags using tag files

Posted on 28-04-2013 22:29 by graham
This tutorial describes how to create custom JSP tags using tag files. This approach is best for simple tags that encapsulate reusable UI with no programmatic logic. If you need a tag that performs some complicated logic, consider creating custom tags with Java files as describes in our tutorial.

Creating a tag file


Let's say we have a piece of HTML code that we use in many places and want to put in a tag file. Let's say this piece of code displays a short menu. To create a tag file, all we need to do is to create a file with the extension .tag and place it in the WEB-INF/tags directory of our application.
simple-menu.tag
<%@ tag description="Simple menu" %>
<%@ attribute name="baseUrl" required="true" rtexprvalue="true" type="java.lang.String" %>

<ul>
<li><a href="${baseUrl}/menu-item-1">Menu Item 1</a></li>
<li><a href="${baseUrl}/menu-item-2">Menu Item 2</a></li>
<li><a href="${baseUrl}/menu-item-3">Menu Item 3</a></li>
</ul>

Using the tag


To use the tag in a JSP page, we need to tell the JSP where to look for tag definitions. We do this by including a taglib pointing to the WEB-INF/tags location:
SomePage.jsp
...
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
...

Then we can use our tag in the JSP code:
SomePage.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>

<%-- include the menu --%>
<tags:simple-menu baseUrl="${pageContext.request.contextPath}" />
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems