Custom Tag example with no attribute and no body
Example program to demonstrate how to make custom tag with no attribute and no body
This example demonstrates how one can make custom tag in JSP that has no attribute and no body. There are only handful of tags in JSP which may not be sufficient for each and every working. You may require to make custom tags which will work according to user requirement. This functionality can be achieved by making a customized tag. For making a customized tag you have to implement Tag interface and you are required to override following methods in your tag class. These are as follows:
- doStartTag()
- doEndTag()
- release()
- setPageContext()
- setParent()
- getParent()
If the TagLibraryDesciptor indicates that tag must always have an empty action by the entry in ".tld" file as <bodycontent> entry of "empty", then doStartTag() method must return SKIP_BODY. Otherwise it may return EVAL_BODY_INCLUDE.
If SKIP_BODY is returned by doStartTag() then if body is present then it is not evaluated. If EVAL_BODY_INCLUDE is returned, the body is evaluated and "passed through" to the current output.
1. emptyTag.java
package mytag;
|
In this emptyTag.java doStartTag() will print "This is an empty tag!" wherever <custom:empty> would be used it will print this line and rest content of body is ignored. To use customized tag you have to make "taglib.tld" file and have to do following entries:
2. taglib.tld
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>custom</shortname> <tag> <name>empty</name> <tagclass>mytag.emptyTag</tagclass> <bodycontent>empty</bodycontent> <info>Tag having no attribute and no body</info> </tag> </taglib> |
To use tag in JSP page you have to write this line:
<%@ taglib uri="/WEB-INF/taglib.tld" prefix="custom" %> |
Full code of JSP page is as follows:
3. CustomTag.jsp
<%@ taglib uri="/WEB-INF/taglib.tld" prefix="custom" %> <html> <head> <title>Custom Tag with no attribute</title> </head> <body bgcolor="ffffcc"> <H1>Welocome ! </H1> Custom tag work starts... <custom:empty/> Custom tag work ends... Body Content of JSP page </body> </html> |
Create and save these above files and start tomcat server. After executing this JSP file you will get output like this:
Output: