JSP Custom Tag Library

We will see here how to create JSP custom tag library. We know JSP tags simplify JSP page development and maintenance works in our day-to-day life. JSP technology also provides a mechanism for encapsulating other types of dynamic functionality in custom tags, which are extensions to the JSP language.

Features of Custom Tags

  • Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control. Custom tags increase productivity because they can be reused in more than one application.
  • Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the objects that implement the tags. The object that implements a custom tag is called a tag handler. JSP technology defines two types of tag handlers: simple and classic.
    • Simple tag handlers can be used only for tags that do not use scripting elements in attribute values or the tag body.
    • Classic tag handlers must be used if scripting elements are required.
  • A tag file is a source file containing a reusable fragment of JSP code that is translated into a simple tag handler by the web container. Tag files can be used to develop custom tags that are presentation-centric or that can take advantage of existing tag libraries, or by page authors who do not know Java. When the flexibility of the Java programming language is needed to define the tag, JSP technology provides a simple API for developing a tag handler in the Java programming language.
  • A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on a tag handler. The web container then invokes those operations when the JSP page’s servlet is executed.
  • Custom tags have a rich set of features. They can
    • Be customized by means of attributes passed from the calling page.
    • Pass variables back to the calling page.
    • Access all the objects available to JSP pages.
    • Communicate with each other.
    • You can create and initialize a Java Beans component, create a public EL (Expression Language) variable that refers to that bean in one tag, and then use the bean in another tag.
    • Be nested within one another and communicate by means of private variables.

For more information please read https://docs.oracle.com/javaee/5/tutorial/doc/bnalj.html

Prerequisites

Eclipse Neon, Apache Tomcat 8.5.39, Java 1.8, Servlet 4, JSP 2, JSTL 1.2

Creating Custom Tag

Now we will see how to create JSP custom tag.

Creating Project

First create a maven or gradle based web project in Eclipse with the below information:

Group Id: com.roytuts
Artifact Id: jsp-custom-tag-library

If you are creating gradle based project then you need to give only project name as jsp-custom-tag-library.

Updating Build File

You have created either maven or gradle based project in Eclipse. So we will see which file we need to use for our application.

build.gradle

If you are using gradle based project then use below build.gradle script for your application.

plugins {
    id 'java-library'
    id 'war'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
	providedCompile("javax.servlet:javax.servlet-api:4.0.1")
	implementation("javax.servlet:jstl:1.2")
	implementation("javax.servlet.jsp:javax.servlet.jsp-api:2.3.3")
}

pom.xml

If you are using maven based project then use below pom.xml file for your application.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.roytuts</groupId>
    <artifactId>jsp-custom-tag-library</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <jdk.version>1.8</jdk.version>
    </properties>
    <dependencies>
        <!-- servlet & jsp -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>jsp</finalName>
        <plugins>
            <!-- maven compiler plugin definition -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Creating Tag Handler Class

Create tag handler class with the below source code.

The attribute name will be used as an input field to the taglib.

package com.roytuts.jsp.custom.tag.library;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class WishTagHandler extends TagSupport {
	private static final long serialVersionUID = 1L;
	private String name;
	@Override
	public int doStartTag() throws JspException {
		JspWriter jspWriter = pageContext.getOut();
		try {
			jspWriter.println("Hello " + name);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Creating Tag Handler File

Create tag handler tld file wishTagHandler.tld under src/main/webapp/WEB-INF/tld/ directory with the below content.

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
    <!-- taglib version -->
    <tlibversion>1.0</tlibversion>
    <!-- jsp version -->
    <jspversion>1.1</jspversion>
    <!-- meaninful short name -->
    <shortname>wish</shortname>
    <!-- taglib description -->
    <info>taglib for displaying name</info>
    <!-- optional -->
    <uri>https://roytuts.com/jsp/taglib/wish</uri>
    <tag>
        <!-- taglib name which will be used as a taglib name -->
        <name>wish</name>
        <!-- taglib class -->
        <tagclass>com.roytuts.jsp.custom.tag.library.WishTagHandler</tagclass>
        <!-- taglib function description -->
        <info>display function</info>
        <!-- taglib attribute -->
        <attribute>
            <name>name</name>
            <required>true</required>
        </attribute>
    </tag>
</taglib>

Creating JSP Page

Create an index.jsp file under src/main/webapp folder to use our custom JSP tag library.

In index.jsp page we have included taglib with prefix test and the actual file in uri section.

<%@taglib prefix="test" uri="/WEB-INF/tld/wishTagHandler.tld"%>
<html>
<head>
<title>JSP Custom Tag Library Example</title>
</head>
<body>
	<font color="blue">
		<test:wish name="Soumitra" />
	</font>
</body>
</html>

Deployment Descriptor

Create a web.xml file under src/main/webapp/WEB-INF folder with below content.

The deployment descriptor file has just one entry – welcome file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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-app_3_1.xsd"
	version="3.1">
	<display-name>JSP Custom Tag Library</display-name>
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Deploying Application

Now deploy the web application into server – Apache Tomcat 8.

Testing the Application

Hit the URL http://localhost:8080/jsp-custom-tag-library/index.jsp in the browser, you will see the page appears with below output in blue color text.

jsp custom tag library

Source Code

download source code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *