Open In App

JSP – Custom URI in Custom Tag

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaServer Pages (JSP) provide a dynamic environment for developing various online applications. Setting the custom Uniform Resource Identifiers (URIs) for custom tags opens up the way for management and organization. While the default pairing of JSP custom tags with URIs based on Java package structures lays the groundwork.

Analysis of a few Aspects

1. Namespace Isolation:

Custom URIs are commonly regarded as simple identifiers. In the world of JSP applications, where custom tags abound, the default association with Java package structures may unintentionally result in naming conflicts. Custom URIs serve as sentinels, providing a level of isolation to guarantee that each collection of custom tags occurs in its namespace.

Syntax Example:

<uri>http://example.com/authentication</uri>

2. Logical Grouping and Organization:

Custom URIs enable developers to create purposeful tag ecosystems, moving beyond simple logical categorization. Architecting bespoke URIs based on functionality, business domain, or purpose helps developers create a modular and understandable codebase. This precise arrangement is beneficial as projects progress, offering a structured canvas on which custom tags correspond with specific modules and capabilities.

Syntax Example:

<uri>http://example.com/paymentProcessing</uri>

3. Clarity in Collaborative Development:

Custom URIs serve as communication documentation in collaborative development. Each URI functions as a guide, directing engineers through the complex maze of code contributions. Custom URIs enable smooth cooperation in team setups where various developers manage separate parts by clearly indicating the origin and purpose of a tag.

Syntax Example:

<uri>http://example.com/collaborativeDevelopment</uri>

In this, developers gain not just a technical understanding but a shared language that collaborates and reduces challenges.

4. Enhanced Readability and Code Comprehension:

The transformation of custom URIs into contextual metadata describes the understanding within JSP pages. As developers encounter custom tags, the associated custom URI helps revealing the tag’s purpose and functionality.

Syntax Example:

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

This transformation transcends traditional code documentation, providing a harmonious blend of organization and comprehension.

5. URI Versioning for Future-Proofing:

Consider incorporating URI versioning as a mechanism for future-proofing custom tags. By including version information in the URI structure, developers ensure compatibility during updates and modifications to the tag library. This practice minimizes potential disruptions and provides a systematic approach to managing changes.

Syntax Example:

<uri>http://example.com/auth/v2</uri>

In this scenario, the URI “http://example.com/auth/v2” indicates a versioned approach, allowing for seamless transitions and updates without affecting existing implementations.

6. URI Security Considerations:

Security considerations play a crucial role in crafting custom URIs. Developers must avoid exposing sensitive information or providing insights into the project’s internal structure. Incorporating secure and non-predictable URI patterns, such as incorporating random strings or hashes, helps protect the namespace and reduce the risk of potential security vulnerabilities.

Syntax Example:

<uri>http://example.com/7fb4a2b8/auth</uri>

In this case, the URI “http://example.com/7fb4a2b8/auth” employs a secure and non-predictable pattern to enhance security.

Exploring Custom URI in JSP Custom Tags: Practical Implementation and Use Cases

Step 1: Dependencies(pom.xml)

<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>

Explanation:

  • The first dependency (jakarta.jakartaee-api) includes the Jakarta EE API, providing core Jakarta EE functionality. It is marked as “provided” because Jakarta EE implementations, like Tomcat or Wildfly, usually provide this API.
  • The second dependency (jakarta.servlet.jsp.jstl-api) includes the JSTL API, which is essential for JSP custom tag support.

Step 2: CustomTagHandler.java

Java
package com.example.customjsptag;

import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.Tag;
import jakarta.servlet.jsp.tagext.TagSupport;

import java.io.IOException;
import java.util.List;

public class CustomTagHandler extends TagSupport {
    private List<String> items; // List of items to display in the table

    public void setItems(List<String> items) {
        this.items = items;
    }

    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();

        try {
            // Generate HTML table
            out.println("<table border='1'>");
            out.println("<tr><th>Index</th><th>Item</th></tr>");

            if (items != null && !items.isEmpty()) {
                for (int i = 0; i < items.size(); i++) {
                    out.println("<tr><td>" + i + "</td><td>" + items.get(i) + "</td></tr>");
                }
            } else {
                out.println("<tr><td colspan='2'>No items to display</td></tr>");
            }

            out.println("</table>");
        } catch (IOException e) {
            throw new JspException(e.getMessage());
        }

        return Tag.SKIP_BODY;
    }
}

Explanation:

  • This is the Java class CustomTagHandler that serves as the tag handler for the custom JSP tag.
  • It extends TagSupport, a base class for tag handlers in JSP.
  • The doStartTag method is invoked when the custom tag is encountered in a JSP page. In this example, it generates an HTML table based on the provided list of items.
  • The setItems method is a setter used to pass the list of items to the tag handler.

Step 3: custom.tld

XML
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">
    <description>Custom Tag Library</description>
    <tlib-version>1.0</tlib-version>
    <short-name>custom</short-name>
    <tag>
        <name>customTag</name>
        <tag-class>com.example.customjsptag.CustomTagHandler</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>items</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

Explanation:

  • This is the tag library descriptor (custom.tld), defining metadata for the custom tag.
  • It specifies the XML namespace (xmlns) and schema location for the TLD file.
  • The <tag> element defines the custom tag. It includes the tag’s name (customTag), the associated tag handler class (com.example.customjsptag.CustomTagHandler), and the body content type (empty).
  • The <attribute> element specifies an attribute (items) that the tag can accept. It is required, and its value can be an expression.

Step 4: web.xml

XML
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">
    <description>Custom Tag Library</description>
    <tlib-version>1.0</tlib-version>
    <short-name>custom</short-name>
    <tag>
        <name>customTag</name>
        <tag-class>com.example.customjsptag.CustomTagHandler</tag-class>
        <body-content>empty</body-content>
    </tag>
</taglib>

Explanation:

  • This is the web.xml file, configuring the custom tag library.
  • It specifies the XML namespace (xmlns) and schema location for the TLD file.
  • The <tag> element defines the custom tag similar to the TLD file, including the tag’s name, associated tag handler class, and the body content type.

Step 5: index.jsp

<%@ page import="java.util.List" %>
<%@ page import="java.util.Arrays" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/custom.tld" prefix="custom" %>
<html>
<head>
<title>Custom Tag Example</title>
</head>
<body>
<%-- Example list of items --%>
<%
List<String> itemList = Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
pageContext.setAttribute("items", itemList);
%>
<custom:customTag items="${items}" />
</body>
</html>

Explanation:

In the above jsp code,

Page Directives:

  • <%@ page import=”java.util.List” %>: This directive imports the List class from the java.util package.
  • <%@ page import=”java.util.Arrays” %>: This directive imports the Arrays class from the java.util package.
  • <%@ page contentType=”text/html;charset=UTF-8″ language=”java” %>: This directive sets the content type of the page to HTML and specifies the character encoding as UTF-8. It also sets the scripting language to Java.

Taglib Directive:

  • <%@ taglib uri=”/WEB-INF/custom.tld” prefix=”custom” %>: This directive declares the custom tag library to be used in the JSP. It specifies the URI of the tag library descriptor (custom.tld) and assigns a prefix (custom) to the tags defined in the library.

Scriptlet Section:

  • <%– Example list of items –%>: This is a JSP comment indicating that the following code block is an example list of items.
  • <% … %>: This is a scriptlet, allowing us to include Java code directly in the JSP. In this block.
  • List<String> itemList = Arrays.asList(“Item 1”, “Item 2”, “Item 3”, “Item 4”);: Creates a list of strings named itemList with four items using Arrays.asList.
  • pageContext.setAttribute(“items”, itemList);: Sets the itemList as an attribute named “items” in the page context. This attribute will be used by the custom tag.

Custom Tag:

  • <custom:customTag items=”${items}” />: This is the usage of the custom tag named customTag from the declared tag library. It passes the list of items (itemList) as an attribute to the custom tag using the expression language (${items}). The custom tag will process this data and generate HTML content accordingly.

Output:

Below in the output, we can see the list has created by Custom Tag.

List create by Custom Tag

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads