JSP Custom Tag

JSP custom tag provides flexibility to programmers, to declare their own tag. Thus, a user-defined tag can be created through custom tags to perform various operations.

These custom tags behave as operations on tag handler when JSP page is translated into servlet. These operations are invoked by web container when servlet of JSP page is executed.

How to create Custom Tag?

These are the steps that you need to follow to create custom tag: –

  • Tag Handler class – Create a tag handler class with .java extension. This class is used to perform operations of custom tag.
  • JSP file – Create a JSP file and include a tag library in it.
  • TLD file – It is required to create tag library file (i.e. TLD file) in WEB-INF directory of your project. This file is represented by .tld extension.

It is required to add both external jars i.e. jsp-api.jar and servlet-api.jar in classpath of your project before deploying the application.

Example of JSP Custom Tag

In this example,

customTagHandler.java

Here, javax.servlet.jsp.tagext.* package contains all the classes that support custom tags and the role of SimpleTagSupport is to provide methods through which JSPWriter object can be accessed.

index.jsp

xyz.tld

Here, the name of tag (message) is given within the <name> tag and the full name of class is given within the <tag-class> tag. The value “empty” given within <body-content> means it doesn’t contain any body.

Output

Note – We can also provide body and attribute within custom tags.

Leave a Comment