Custom tag library descriptor exampletags. TLD
<? 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> example </short-Name> <description> custom tag library description </description> <URI>/WEB-INF/TLDs/exampletags </uri> <tag> <Name> iterate </Name> <tag-class> tags. freetag </Tag-class> </Tag> <tag> <Name> time </Name> <tag-class> tags. datetag </Tag-class> </Tag> </taglib>
Freetag. Class
package tags; import Java. io. ioexception; import Java. util. logging. level; import Java. util. logging. logger; import javax. servlet. JSP. jspexception; import javax. servlet. JSP. tagext. tagsupport;/***** @ author JY */public class freetag extends tagsupport {private int arraycount = 0; private string [] strings = NULL; @ overridepublic int dostarttag () throws jspexception {strings = (string []) pagecontext. getattribute ("strings"); Return eval_body_include;} @ override public int doafterbody () throws jspexception {try {pagecontext. getout (). print ("" + strings [arraycount] + "
");} catch (ioexception ex) {logger. getlogger (freetag. class. getname ()). log (level. severe, null, ex);} arraycount ++; If (arraycount> = strings. length) {return skip_body;} return eval_body_again ;}}
Datetag. Class
Package tags; import Java. io. ioexception; import Java. text. simpledateformat; import Java. util. logging. level; import Java. util. logging. logger; import javax. servlet. JSP. tagext. tagsupport;/***** @ author JY */public class datetag extends tagsupport {@ override public int doendtag () {simpledateformat format = new simpledateformat ("HH: mm: SS "); string time = format. format (New Java. util. date (); try {pagecontext. getout (). print (time);} catch (ioexception ex) {logger. getlogger (datetag. class. getname ()). log (level. severe, null, ex);} return eval_page ;}}
Test. jsp
<% @ page contenttype = "text/html" pageencoding = "UTF-8" %> <% @ taglib prefix = "example" uri = "/WEB-INF/TLDs/exampletags. TLD "%>
JSP page Hello world!
<% string [] strings = new string [] {"A", "B", "C"}; pagecontext. setattribute ("strings", strings); %>
now time: