JSP taglib directive

JSP taglib directive is used in case of custom tags. It specifies the tag library used for custom tags. We will learn more about taglib directives in the custom tag section.

 

Attributes of JSP taglib directive:

  1. uri: This attribute specifies the location of the tag library.
  2. prefix: This attribute is to inform the web container that this markup is used for custom actions.

 

Syntax:

<%@ taglib uri="uri" prefix="prefixForCustomTag">

 

Example:

CustomTag.java

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * This class is used for defining a custom tag.
 * @author W3schools360
 */
public class CustomTag extends SimpleTagSupport{
	public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.println("This is our first custom tag.");
   }
}

 

firsttag.tld

<taglib>
     <tlib-version>1.0</tlib-version>
     <jsp-version>2.0</jsp-version>
     <short-name>Our first custom tag</short-name>
 
     <tag>
        <name>firstTag</name>
        <tag-class>com.w3schools360.customtags.CustomTag</tag-class>
        <body-content>empty</body-content>
     </tag>
</taglib>

 

test.jsp

<%@ taglib prefix="ftag" uri="WEB-INF/firsttag.tld"%>
 
<html>
    <head>
        <title>custom tag example</title>
    </head>
    <body>
        <ftag:firstTag/>
    </body>
</html>

 

web.xml

<web-app>
 
  <welcome-file-list>
          <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>	
 
</web-app>