In this tutorial you will learn about the JSP Taglib Directive and its application with practical example.
JSP Taglib Directive
The taglib directive is used to define a tag library in which we can defines many tags. The JSP allows us to define custom tag and with the help of Tag Library Descriptor(TLD) we can define our tags.
Syntax:
1 |
<%@taglib uri ="taglibURI" prefix="tag prefix"%> |
Example: :Let’s get understand it by an example, we need to follow some steps for creation our own tag, see below.
#Need to create TagHandler java class: With the help of this class we can perform action at the start and at the end of tag. Check below code.
MyTagHandler.java: This is the java file which I created for TagHandler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package w3adda; 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 { @Override public int doStartTag() throws JspException { JspWriter out = pageContext.getOut();//it will returns the instance of JspWriter try { out.print(Calendar.getInstance().getTime());//this will used to print date and time using JspWriter } catch (Exception e) { System.out.println(e); } return SKIP_BODY; } } |
#Need to create TLD(Tag Library Descriptor): Here we will define our tag.
1.step: do right click on your project and then “New>Tag Library Descriptor” like below image.
If you are unable to find here click on “Other” and then “Web>Tag Library Descriptor” like below image.
2.Step:Click on Next and define your tld file name,and then finish it, like below image
3.step: Define Tag: After creation tld file we have to define our tag here like i did, please check below code.
customtag.tld:
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="UTF-8"?> <taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"> <tlib-version>1.0</tlib-version> <short-name>customtag</short-name> <uri>/customtag</uri> <tag> <name>today</name> <tag-class>w3adda.MyTagHandler</tag-class> </tag> </taglib> |
#Create JSP file: In this file we will use our custom tag.create a jsp file and paste below code there.
Index.jsp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="WEB-INF/customtag.tld" prefix="m" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>W3Adda Page</title> </head> <body> Current Date and Time is: <m:today/> </form> </body> </html> |
#Run: So we all set with taglib directive, Simply run this project you will get output like below image.