Reading:
Custom tags in JSP

Custom tags in JSP

Metamug
Custom tags in JSP

Custom Tags in JSP

Custom tags are just user defined tags in JSP. These tags provide a convenient way to perform some operations, it also separates the working logic from the JSP page, so it becomes more easy to maintain.

When the JSP engine come across a custom tag it executes the Java code that is used for it.

For a working Custom tag we need mainly 3 files.

  • A tag handles class
  • A tld file
  • and obviously the JSP file

Let's see an example for this

The tag handler class

This class contains the main working logic of our custom tag. To write this class we extend SimpleTagSupport class and override the doTag() method.

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class HelloCustomTag extends SimpleTagSupport {

    @Override
    public void doTag() throws JspException {
        JspWriter out = getJspContext().getOut();
        out.println( "Hello Custom Tags." );
    }
}

This class prints out Hello Custom Tags.\ To write data for the jsp we need JspWriter object and here we get that from the getJspContext method of SimpleTagSupport class

The tld file

The tld (Tag Library Descriptor) file contains information about the tag and the tag handler class. It can contain one or more tag definitions. The tag definition is written inside the tag, and it must contain the tag name and tag handler class.

<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.metamug.examples.HelloCustomTag</tag-class>
        <body-content>empty</body-content>
    </tag>
</taglib>

This file must be in the WEB-INF directory.

The JSP file

In the JSP file, we declare the custom prefix name and the location of the tag handler class. It uses taglib directive to use the tags defined in the tld file.

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

JSP says  <m:Hello/>

This JSP will produce the following result

JSP says Hello Custom Tags



Icon For Arrow-up
Comments

Post a comment