A JSP tag is a tag that you can embed in your JSP page just like regular HTML tags (e.g., the <table> tag). However, your JSP tag is not sent to the browser. Instead, it is evaluated by the JSP engine on the server side. The output of your tag is inserted into the page at the location where the tag was embedded.

Three Reasons to Create JSP Tags

  1. JSP tags allow you to move complicated code out of your JSP file.
  2. JSP tags allow you to write code once and use it in many JSP files.
  3. JSP tags are written in Java so you have access to better control statements and generate more efficient code.

A simple example

To create a tag that converts its text argument to uppercase, the JSP file looks like this:

<%@ page contentType="text/html" language="java" %>
<%@ taglib prefix="ng" uri="/WEB-INF/tld/nextgen.tld" %>
<ng:upperCase text="lowercase text" />

Tags need to be defined before you can use them. They are defined in tag libraries. To create a tag library named nextgen, you need to create a Tag Library Definition file (TLD):

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">



This tag file defines one tag (upperCase) that is implemented by the class UpperCaseTag and takes one String argument named text. Now you need to write the Java code to implement your tag:

public class UpperCaseTag extends SimpleTagSupport {
  private String text;
  public void setText(String value) { text = value; }

  public void doTag() throws JspException, IOException {


By extending the SimpleTagSupport class the task was fairly easy.


J2EE Tutorial Chapter 7