We have an example of how to customize the JSP tag, if we need to output the current time in the page, according to the simplest JSP script, need to write a lot of Java code in the jsp, then how to use custom tags to implement this function?
first, we'll Start by creating a class that inherits the TagSupport Class:
1 Importjava.io.IOException;2 Importjava.text.SimpleDateFormat;3 Importjava.util.Date;4 Importjavax.servlet.jsp.JspException;5 Importjavax.servlet.jsp.tagext.TagSupport;6 7 public classLogindatetagextendsTagSupport {8 9 @OverrideTen public intdoStartTag ()throwsjspexception { oneSimpleDateFormat SDF =NewSimpleDateFormat ("YYYY-MM-DD HH:mm:ss"); aString date = Sdf.format (NewDate ()); - Try { - pagecontext.getout (). Print (date); the}Catch(ioexception E) { - e.printstacktrace (); - } - return Super. doStartTag (); + } - +}
The second step is to set the. TLD file, The template of the TLD file can be found in tomcat, C:\Program files\apache-tomcat-7.0.56\webapps\examples\web-inf\jsp2, Jsp2-example-taglib.tld file:
1 <?XML version= "1.0" encoding= "UTF-8"?>2 <taglibxmlns= "http://java.sun.com/xml/ns/j2ee"3 Xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemalocation= "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"5 version= "2.0">6 <Description>A Tag Library exercising Simpletag Handlers.</Description>7 <tlib-version>1.0</tlib-version>8 <Short-name>Simpletaglibrary</Short-name>9 <URI>/test</URI>//path to import this fileTen <Tag> one <name>Logindate</name>//tag name a <Tag-class>Util. Logindatetag</Tag-classClass of >//tag function code - <body-content>Empty</body-content> - </Tag> the </taglib>
Once the configuration is complete, you can call our custom tags in the JSP code
1 <%@ Page Language="Java"Import="java.util.*"ContentType="text/html; Charset=utf-8"%>2<!--import Custom Tag libraries-->3 <%@ taglib Prefix="T"URI="/test" %>4 <!DOCTYPE HTML public "-//w3c//dtd HTML 4.01 transitional//en">5 <HTML>6 <Body>7Your log-in time is:<t:logindate/>8 </Body>9 </HTML>
Sample Custom JSP Tags