Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A custom tag is a JSP language element that the user has defined. When a JSP page with a custom tag is converted to a servlet, the tag is transformed into operations on a tag handler object. When the JSP page's servlet is executed, the Web container calls those operations.
Tag extensions for JSP allow you to build new tags that may be immediately inserted into a JavaServer Page. Simple Tag Handlers were created in the JSP 2.0 specification for authoring these custom tags.
To create a custom tag, simply extend SimpleTagSupport and override the doTag() method, where you may put your code to generate tag content.
To use a custom tag, use the following syntax:
The custom tag can be used in two ways. They are as follows:
<prefix:tag name attr1=value1.... attr = value />
<prefix:tag name attr1=value1.... attr = value>
body code
</prefix:tagname>
We'll need three things to make a custom tag:
1. Tag handler class: We define what our custom tag will do when used in a JSP page in this class.
2. Tag descriptor file (TLD): Itcontains the tag name, tag handler class, and tag attributes.
3. JSP page: This is the JSP page where we'll use our custom tag.
Classes and interfaces for the JSP custom tag API can be found in the javax.servlet.jsp.tagext package. In the Custom Tag hierarchy, the JspTag is the root interface.
JspTag Interface
JspTag is the root interface for all of the custom tag's interfaces and classes. It's a marker-based user interface.
Tag Interface
Jsp Tags Tag interface is a subinterface of JspTag. It includes ways for taking action at the beginning and conclusion of the tag.
Tag interface fields
In the Tag interface, there are four fields defined. They are as follows:
Field Name
Description
public static int EVAL_BODY_INCLUDE
It assesses the body's contents.
public static int EVAL_PAGE
After the custom tag, it examines the JSP page content.
public static int SKIP_BODY
It skips through the tag's body information.
public static int SKIP_PAGE
After the custom tag, it skips the JSP page content.
Tag interface methods
The Tag interface has the following methods:
Method Name
Description
public void setPageContext(PageContext pc)
It creates a PageContext object with the supplied parameters.
public void setParent(Tag t)
It determines the tag handler's parent.
public Tag getParent()
It returns the tag handler object for the parent tag.
public int doStartTag()throws JspException
The JSP page implementation object uses it to call it. The JSP programmer should override this function and define the business logic that will be executed at the beginning of the tag.
public int doEndTag()throws JspException
The JSP page implementation object uses it to call it. The JSP programmer should override this function and specify the business logic that will be executed at the tag's end.
public void release()
The JSP page implementation object calls it to release the state.
Advantages of Using Custom Tags
The following are the main benefits of custom tags:
1. Removes the necessity for the scriptlet tag: The scriptlet tag is no longer required, which is considered a bad programming practice in JSP.
2. Business logic is separated from JSP: The custom tags keep the business logic separate from the JSP page, making it easier to maintain.
3. Adaptability: The custom tags allow you to reuse the same business logic repeatedly.
This is the first step in using JSP to create custom tags. We inherit the TagSupport class and override the function doStartTag() to create the Tag Handler. The JspWriter class is used to write data to the JSP.
The getOut() method of the PageContext class returns an instance of the JspWriter class. By default, the TagSupport class gives a pageContext instance.
ThisIsTagHandler.java
package com.mycustomtag.sonoo;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends TagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();//JspWriter's instance is returned.
try{
out.print(Calendar.getInstance().getTime());//JspWriter is used to print the date and time.
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;//The tag's body content will not be evaluated.
}
}
You can also try this code with Online Java Compiler
Creating a TLD (Tag Library Descriptor) File in JSP
Once the tag handler class is complete, we must create a TLD file in the WEB-INF directory, which will be loaded by the container when the application is deployed.
Tag and Tag Handler classes are described in the Tag Library Descriptor (TLD) file.
The URI element should be noted; we'll need to define it in our deployment description file. It's also worth noting that the characteristics, format and number are essential. If body content is empty, the tag will have no content.
Creating a page using JSP Custom Tag
In our JSP file, let's use the tag. We are directly supplying the path of the TLD file here. However, it is preferable to use the URI name instead of the complete path to the TLD file.
The tags defined in the TLD file are used using the taglib directive.
index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Current Date and Time is: <m:today/>
After executing the code we get the following output:
Custom Tag Attributes
Along with your unique tags, you may use a variety of attributes. A custom tag class must implement the setter methods, which are the same as the JavaBean setter methods, in order to receive an attribute value.
package com.customtagmine;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class MyTag 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) {
JspWriter out = getJspContext().getOut();
out.println( message );
} else {
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
}
You can also try this code with Online Java Compiler
The setter method for the attribute "message" is setMessage (). Now, using the <attribute> element, let's add this attribute to the TLD file as follows:
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>TLD’s example with Body</short-name>
<tag>
<name>Hi</name>
<tag-class>com.customtagmine.MyTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
Let's have a look at JSP with the message attribute.
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>
<html>
<head>
<title>A example of custom tag</title>
</head>
<body>
<ex:Hello message = "This is a example of custom tag" />
</body>
</html>
As a result, you'll get the following outcome:
This is a example of custom tag
Consider adding the properties below to an attribute:
S.No.
Property & Purpose
1
name
An attribute's name is defined by the name element. For each tag, each attribute name must be unique.
2
required
This indicates whether this attribute is essential or optional. For optional, it would be false.
3
rtexprvalue
Declares whether a tag attribute's runtime expression value is legitimate.
4
type
This attribute's Java class-type is defined. It is considered to be String by default.
5
description
It is possible to provide an informative description.
6
fragment
Declares whether the value of this attribute should be regarded as a JspFragment.
The following is an example of how to specify properties for an attribute.
A custom tag is a JSP language element that the user has defined. When a JSP page with a custom tag is transformed to a servlet, the tag is converted to tag handler operations. The web container calls those operations when the JSP page's servlet is executed.
Custom tags come with a lot of options. They can
The properties passed from the calling page can be changed.
Return the variables to the caller page.
All of the items available to JSP pages can be accessed.
Make an effort to communicate with one another. You can construct and initialise a JavaBeans component, then utilise it in another tag by referencing it with a public EL variable.
Be nested within one another and communicate through the private variables.
2. To create a custom tag, what do we need?
Three items are required to generate a custom tag:
1) Tag handler class: In this class, we indicate what our custom tag will do on a JSP page when it is used.
2) Tag descriptor file (TLD) contains the tag name, tag handler class, and tag attributes.
3) JSP page: We'll use our custom tag on a JSP page.
3. What is the JspTag interface?
The Tag interface specifies how a Tag handler and a JSP page implementation class communicate. It specifies the life cycle as well as the methods that will be called at the start and end tags.
4. Write one advantage of using a custom tag?
The scriptlet tag is no longer required. In JSP, the scriptlet tag is no longer required, as it is considered a bad programming technique.
5. What are custom tag attributes?
You can use a multitude of qualities in addition to your unique tags. To accept an attribute value, a custom tag class must implement the setter methods, which are the same as the JavaBean setter methods.
Key Takeaway
JSP Custom tags are tags defined by the user that enhance the capability of JSP. They are easy to use, effectively encapsulating the features. They are simple to comprehend and use, so even non-expert page authors can use them. We looked at many custom tags and their approaches in this article.
We have seen the advantages of using Custom tags and how we use them with the help of a simple example. If you want to get started with JSP then you can check out the article on JSP Syntax and First App.