Webucator blogs about online learning and training.

Tag files contain JSP elements that define a custom action. A JSP tag file is similar to a normal JSP file with three exceptions:

  1. The page directive is not allowed in a tag file.
  2. There are certain JSP directives that are only allowed in a tag file.
  3. The file name extension for a tag file is “.tag”.

Everything else is the same as creating a JSP page.

Using custom JSP tag files provide a number of benefits:

  1. Promotes reusability
  2. Enhances loose coupling
  3. Creates single point of maintenance
  4. Allows a clear division of labor between technical and esthetic skill sets

The following is a JSP page that uses a custom tag. For all intents and purposes, it eliminates coding from the page with the exceptions of the directives and the me prefix on the sayHello element.

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="me" tagdir="/WEB-INF/tags" %>


	
		
	
	
		
	

When this page is viewed in a browser, it will provide the following display:
Hello with Custom JSP tag

Here is the custom tag (sayHello.tag) used in the JSP example page above:

<%@ tag body-content="empty" %>
<%@ attribute name="firstName" required="true" rtexprvalue="true" %>
<%@ attribute name="lastName" required="true" rtexprvalue="true" %>



Note the directives. They declare the required attributes firstName and lastName. These attributes were used in expressions to set the values on a JavaBean. Here is the JavaBean (YourName.java) used by this tag:

package com.webucator.beans;
public class YourName {
	private String firstName;
	private String lastName;
	public YourName() {}
	public String getGreeting() {
		return "

Hello, " + firstName + " " + lastName + "!

"; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } }

This brings me back to the benefits or custom JSP tags that I listed at the beginning of this article:

  1. Promotes reusability: The tag can be used in any number of JSP pages that need it.
  2. Enhances loose coupling: The JSP page is completely decoupled from the underlining code.
  3. Creates single point of maintenance: Changes made to the tag will also change the JSP documents that use it.
  4. Allows a clear division of labor between technical and aesthetic skill sets: It frees page designers to deal with design while freeing programmers to focus on programming.
  5. In short, it is a win/win proposition for web application development in general.

    In my upcoming articles I will cover Java frameworks in general and explore the most popular.

    Custom tags are covered in our Introduction to JSP, Advanced JSP, and Comprehensive JSP classes.

Comments are closed.

© Webucator, Inc. All rights reserved. | Toll Free: 877-932-8228 | Outside the USA: 315-849-2724 | Fax: 315-849-2723