JSTL custom tag and jstl custom tag
When the JSTL tag library cannot meet our needs, we need to develop custom tags to meet our needs. Custom tags are actually a common java class, inherits the SimpleTagSupport class.
Class. Derived from SimpleTagSupport, override the doTag () method. GetJspBody (), getJspContext (), invoke (null );
Package com. itnba. maya. zidingyi; import java. io. IOException; import javax. servlet. jsp. jspException; import javax. servlet. jsp. tagext. *; public class Zidingyijstl extends SimpleTagSupport {private String a = "p"; public void setA (String a) {this. a = a;} private int B; public void setB (int B) {this. B = B;} public void doTag () throws JspException, IOException {// rewrite doTage () method JspFragment frag = this. getJspBody (); this. getJspContext (). getOut (). write ("<" + a + ">"); for (int I = 0; I <B; I ++) {frag. invoke (null);} this. getJspContext (). getOut (). write ("</" + a + "> ");}}
Create a tld file (myjstl. tld) in the WEB-INF directory of the web project. This tld file is the declaration file of the tag library, and configure the corresponding information. (Refer to the tld file of the core tag library)
<? Xml version = "1.0" encoding = "UTF-8"?> <Taglib 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" version = "2.1"> <description> Custom tags </description> <display-name> Custom tags </display-name> <tlib -version> 1.0 </tlib-version> <short-name> m </short-name> <uri> http://www.itnba.com/maya/myjst L </uri> <tag> <description> description </description> <name> show </name> <! -- Tag name --> <tag-class> com. itnba. maya. zidingyi. Zidingyijstl </tag-class> <! -- Unique identifier --> <body-content> scriptless </body-content> <! -- The script cannot be written in the tag <%> --> <! -- Add Property --> <attribute> <description> This is the description of the custom tag. You can prompt </description> <name> a </name> <! -- Attribute name, which must correspond to the method name --> <required> false </required> <! -- Required? --> <rtexprvalue> false </rtexprvalue> <! -- Can an EL expression be used in a tag? --> </attribute> <! -- Write another method --> <attribute> <description> This is the description of the custom tag. You can prompt in MyEclipse. </description> <name> B </name> <! -- Attribute name, which must correspond to the method name --> <required> true </required> <! -- Required? --> <rtexprvalue> false </rtexprvalue> <! -- Can an EL expression be used in a tag? --> </attribute> </tag> </taglib>
Jsp page
<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" m "uri =" http://www.itnba.com/maya/myjstl "%> <% -- configure -- %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
Display