Custom Tags

JSP and JavaBeans provide a nice way to abstract data access away from the page itself, but it still doesn’t get code entirely out of the system. Page designers still must use script elements for control functions such as loops or branching logic. In addition, JavaBeans sometimes aren’t enough to fully encapsulate a web application’s internal logic, leaving large chunks of code embedded in JSPs. And of course, there’s the matter of code reuse. While utility methods can be abstracted out into classes and made available to JSPs, scripting code embedded within a particular JSP tends not to lend itself to abstraction.

The JSP specification addresses this by allowing the creation of custom tags. Tags are organized into Tag Libraries, which can be loaded by pages as needed. Each tag library gets its own namespace, and can be shared by as many pages as necessary. Properly designed custom tags can cut most, if not all, of the remaining pure Java code out your JSPs.

Imagine a simple tag that displays the current date and time. Let’s call the tag Date. After creating and configuring it, we can access it within a JSP page:

<enterprise:Date/>

Note that the namespace is no longer jsp. Instead, we have a custom specified namespace that identifies a tag library, or taglib, containing a set of custom tags. We declare the tag library at the beginning of the JSP file with the <%@ taglib %> directive:

<%@ taglib uri="http://ora.com/enterprise/ examples-taglib" prefix="enterprise"%> ...

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.