Java.Servlets.Give an example of using your own tags.

I’ll show you how to:

  • Write a Java class for the tag
  • Configure a TLD file (Tag Library Descriptor)
  • Use your custom tag inside a JSP page
  • Pass a parameter (attribute) to the tag

🎯 Goal:

We will create a custom tag <my:greet name="Stanley" />
that outputs:

Hello, Stanley!

🔵 Step 1: Write the Java Class for the Tag

Create a Java class that extends SimpleTagSupport.

File: GreetTag.java

package mytags;

import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;

public class GreetTag extends SimpleTagSupport {
    private String name;

    // Setter (for the attribute 'name')
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void doTag() throws IOException {
        JspWriter out = getJspContext().getOut();
        if (name != null) {
            out.write("Hello, " + name + "!");
        } else {
            out.write("Hello, Guest!");
        }
    }
}

Important:

  • The method setName(String name) is automatically called when you use name="..." in the tag!
  • doTag() defines what the tag will output.

🔵 Step 2: Create a TLD File

Create a TLD (Tag Library Descriptor) file that describes your tag.

File: /WEB-INF/mytags.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>MyTags</short-name>
    <uri>http://example.com/mytags</uri>

    <tag>
        <name>greet</name>
        <tag-class>mytags.GreetTag</tag-class>
        <body-content>empty</body-content>

        <attribute>
            <name>name</name>
            <required>false</required>
        </attribute>
    </tag>
</taglib>

✅ Key things:

  • name: how you will call the tag (greet)
  • tag-class: full class name (including package)
  • attribute name="name": defines the tag’s parameter

🔵 Step 3: Use the Custom Tag in a JSP Page

Now, use your custom tag in a JSP page!

File: greet.jsp

<%@ taglib uri="http://example.com/mytags" prefix="my" %>

<html>
<head><title>Custom Tag Example</title></head>
<body>

<!-- Use our custom tag -->
<my:greet name="Stanley" />

<br>

<!-- Without providing name -->
<my:greet />

</body>
</html>

✅ Output:

Hello, Stanley!
Hello, Guest!

📜 Summary of What We Did:

StepWhat We Created
Java Tag HandlerGreetTag.java (the logic)
Tag Library Descriptormytags.tld (the description)
JSP Pagegreet.jsp (the usage)

Now you have your own custom JSP tag working!

📢 Notes:

  • You can add multiple attributes by writing more setters in Java (setXxx()).
  • You can create tags with a body (using <jsp:doBody/>) if you need more advanced behavior.
  • In modern apps, tag files (.tag) are sometimes used instead of Java classes for simple cases.
This entry was posted in Без рубрики. Bookmark the permalink.