Custom Tags in JSP

Last updated on May 31 2022
Mohnish Patil

Table of Contents

Custom Tags in JSP

In this blog, we will discuss the Custom Tags in JSP. 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 an object called a tag handler. The Web container then invokes those operations when the JSP page’s servlet is executed.

JSP tag extensions lets you create new tags that you can insert directly into a JavaServer Page. The JSP 2.0 specification introduced the Simple Tag Handlers for writing these custom tags.

To write a custom tag, you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.

Create “Hello” Tag

Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion without a body −

<ex:Hello />

To create a custom JSP tag, you must first create a Java class that acts as a tag handler. Let us now create the HelloTag class as follows −

package com.tecklearn;




import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;




public class HelloTag extends SimpleTagSupport {

   public void doTag() throws JspException, IOException {

      JspWriter out = getJspContext().getOut();

      out.println("Hello Custom Tag!");

   }

}

The above code has simple coding where the doTag() method takes the current JspContext object using the getJspContext() method and uses it to send “Hello Custom Tag!” to the current JspWriter object

Let us compile the above class and copy it in a directory available in the environment variable CLASSPATH. Finally, create the following tag library file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.

<taglib>

   <tlib-version>1.0</tlib-version>

   <jsp-version>2.0</jsp-version>

   <short-name>Example TLD</short-name>

  

   <tag>

      <name>Hello</name>

      <tag-class>com.tecklearn.HelloTag</tag-class>

      <body-content>empty</body-content>

   </tag>

</taglib>

Let us now use the above defined custom tag Hello in our JSP program as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>




<html>

   <head>

      <title>A sample custom tag</title>

   </head>

  

   <body>

      <ex:Hello/>

   </body>

</html>

Call the above JSP and this should produce the following result −

Hello Custom Tag!

Accessing the Tag Body

You can include a message in the body of the tag as you have seen with standard tags. Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion with a body −

<ex:Hello>

This is message body

</ex:Hello>

Let us make the following changes in the above tag code to process the body of the tag −

package com.tecklearn;




import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;




public class HelloTag extends SimpleTagSupport {

   StringWriter sw = new StringWriter();

   public void doTag()

  

   throws JspException, IOException {

      getJspBody().invoke(sw);

      getJspContext().getOut().println(sw.toString());

   }

}

Here, the output resulting from the invocation is first captured into a StringWriter before being written to the JspWriter associated with the tag. We need to change TLD file as follows −

<taglib>

   <tlib-version>1.0</tlib-version>

   <jsp-version>2.0</jsp-version>

   <short-name>Example TLD with Body</short-name>

 

   <tag>

      <name>Hello</name>

      <tag-class>com.tecklearn.HelloTag</tag-class>

      <body-content>scriptless</body-content>

   </tag>

</taglib>

Let us now call the above tag with proper body as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>




<html>

   <head>

      <title>A sample custom tag</title>

   </head>

  

   <body>

      <ex:Hello>

         This is message body

      </ex:Hello>

   </body>

</html>

You will receive the following result −

This is message body

Custom Tag Attributes

You can use various attributes along with your custom tags. To accept an attribute value, a custom tag class needs to implement the setter methods, identical to the JavaBean setter methods as shown below −

package com.tecklearn;




import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;




public class HelloTag extends SimpleTagSupport {

   private String message;




   public void setMessage(String msg) {

      this.message = msg;

   }

   StringWriter sw = new StringWriter();

   public void doTag()

  

   throws JspException, IOException {

      if (message != null) {

         /* Use message from attribute */

         JspWriter out = getJspContext().getOut();

         out.println( message );

      } else {

         /* use message from the body */

         getJspBody().invoke(sw);

         getJspContext().getOut().println(sw.toString());

      }

   }

}
The attribute's name is "message", so the setter method is setMessage(). Let us now add this attribute in the TLD file using the <attribute> element as follows −

<taglib>

   <tlib-version>1.0</tlib-version>

   <jsp-version>2.0</jsp-version>

   <short-name>Example TLD with Body</short-name>

  

   <tag>

      <name>Hello</name>

      <tag-class>com.tecklearn.HelloTag</tag-class>

      <body-content>scriptless</body-content>

     

      <attribute>

         <name>message</name>

      </attribute>

  

   </tag>

</taglib>

Let us follow JSP with message attribute as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>




<html>

   <head>

      <title>A sample custom tag</title>

   </head>

  

   <body>

      <ex:Hello message = "This is custom tag" />

   </body>

</html>

This will produce following result −

This is custom tag

Consider including the following properties for an attribute −

S.No. Property & Purpose
1 name

The name element defines the name of an attribute. Each attribute name must be unique for a particular tag.

2 required

This specifies if this attribute is required or is an optional one. It would be false for optional.

3 rtexprvalue

Declares if a runtime expression value for a tag attribute is valid

4 type

Defines the Java class-type of this attribute. By default it is assumed as String

5 description

Informational description can be provided.

6 fragment

Declares if this attribute value should be treated as a JspFragment.

Following is the example to specify properties related to an attribute −

 

   <attribute>

      <name>attribute_name</name>

      <required>false</required>

      <type>java.util.Date</type>

      <fragment>false</fragment>

   </attribute>

 

If you are using two attributes, then you can modify your TLD as follows −

   <attribute>

      <name>attribute_name1</name>

      <required>false</required>

      <type>java.util.Boolean</type>

      <fragment>false</fragment>

   </attribute>

  

   <attribute>

      <name>attribute_name2</name>

      <required>true</required>

      <type>java.util.Date</type>

   </attribute>

 

 

So, this brings us to the end of blog. This Tecklearn ‘Custom Tags in JSP’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn JSP and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Custom Tags in JSP"

Leave a Message

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