O'Reilly logo

Java Enterprise in a Nutshell, Second Edition by David Flanagan, Jim Farley, William Crawford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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"%> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required