Detailed description of custom Taglib in jsp and detailed description of jsptaglib

Source: Internet
Author: User

Detailed description of custom Taglib in jsp and detailed description of jsptaglib

1. Getting started with custom tags without parameter custom tags

1. develop custom tag classes

When we use a simple tag on a JSP page, the underlying layer is actually supported by the tag processing class, so that we can use simple tags to encapsulate complex functions, in this way, the team can better collaborate in Development (which allows the artist to better participate in the development of JSP pages ).

The custom label class must inherit a parent class: javax. servlet. jsp. tagext. SimpleTagSupport, or TagSupport. In addition, the JSP custom label class also has the following requirements.

If the tag class contains attributes, each attribute has the corresponding getter and setter methods.

Override the doTag (), doStartTag (), or doEndTag () method to generate page content.

The following describes a tag without attributes. Take HelloWorld as an example:

The Java code is as follows:

public class HelloWorldTag extends TagSupport {   private static final long serialVersionUID = -3382691015235241708L;  @Override  public int doEndTag() throws JspException {    try {      pageContext.getOut().write("Hello World !");      return super.doEndTag();    } catch (JspException e) {      e.printStackTrace();      return 0;    } catch (IOException e) {      e.printStackTrace();      return 0;    }  }   @Override  public int doStartTag() {    try {      pageContext.getOut().write("Hello World");      return super.doStartTag();    } catch (JspException e) {      e.printStackTrace();      return 0;    } catch (IOException e) {      e.printStackTrace();      return 0;    }  }}

Note:

Question 1: What are the differences between dostartTag and doEndTag in tagsupport?
DoStartTag is called when the start tag is scanned, while doEndTag is called when the end tag is scanned.
Example: The jsp Engine calls doStratTag when analyzing

2. Create a TLD File

TLD is the abbreviation of Tag Library Definition, that is, the Tag Library Definition. The file suffix is tld. Each TLD file corresponds to a Tag Library. A Tag Library can contain multiple tags, a tld file is also called a tag library definition file.

The root element of the tag library definition file is taglib, which can contain multiple tag sub-elements. Each tag sub-element defines a tag. Generally, we can copy a tag library definition file under a Web Container and modify the file. For example, Tomcat6.0 contains a WEB-INF file under the webapps \ examples \ jsp2-example-taglib.tld \ jsp2 path, which is the tag library definition file used for demonstration.

Copy the file to the WEB-INF/path of the Web application, or any sub-path of the WEB-INF, and make simple modifications to the file. The modified helloworld. tld file code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Taglib xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd" version = "2.0"> <tlib-version> 1.0 </tlib-version> <short-name> myhelloworld </short-name> <! -- The URI that defines the tag library must be added but can be empty --> <uri> </uri> <! -- Define the first tag --> <tag> <! -- Define the tag name --> <name> helloWorld </name> <! -- Define the tag processing class --> <tag-class> org. lxh. taglib. HelloWorldTag </tag-class> <! -- Empty tag definition --> <body-content> empty </body-content> </tag> </taglib>

Question 1: why should we use TagSupport and BodyTagSupport? The main difference is whether the label processing class needs to interact with the label body. If no interaction is required, use TagSupport; otherwise, use BodyTagSupport.

Interaction is whether the tag processing class needs to read the content of the TAG body and change the content returned by the TAG body. All labels implemented using TagSupport can be implemented using BodyTagSupport, because BodyTagSupport inherits TagSupport and does not implement the IterationTag interface, because BodyTagSupport inherits the TagSupport class, this class has implemented the IterationTag interface and implemented functions.

The doStartTag () method is executed when the tag starts. Remember to initialize the class every time to avoid the impact of the previous legacy data on the operation. Then determine whether there is data to be processed. If yes, return EVAL_BODY_INCLUDE to start processing the content in the tag. If not, return EVAL_PAGE to skip the label content and execute the content below the tag.

The doAfterBody () method is executed after the internal content of the tag is processed each time to determine whether the loop has ended. If the loop can be continued, the EVAL_BODY_AGAIN method is returned to obtain new data and process the internal content of the TAG again, if the loop ends, the EVAL_PAGE end tag is returned.

Ii. Processing of custom JSP labels:

1. Introduce the tag library in JSP:
2. Use tag library tags in JSP
3. The Web Container obtains the uri attribute value of taglib declared in the first step based on the prefix in the second step.
4. The Web Container finds the corresponding element in web. xml based on the uri attribute.
5. Obtain the value of the corresponding element from the element
6. Web containers find the corresponding. tld file from the WEB-INF/directory based on the element value
7. Find the corresponding tagname element from the. tld file.
8. Obtain the value of the corresponding element from the elements.
9. The Web Container creates the corresponding tag handle class instance based on the element value.
10. The Web Container calls the doStartTag/doEndTag method of this instance to complete corresponding processing.

3. Basic Steps for creating and using a Tag Library:

1. Tag Handler Class)
2. Create a Tag Library description File (Tag Library Descrptor File)
3. Configure elements in the web. xml file
4. Add a tag Library to the JSP file

Iv. Introduction to TagSupport:

1. The class for processing tags must extend javax. servlet. jsp. TagSupport.

2. Main attributes of the TagSupport class:

A. parent attribute: indicates the processing class of the Upper-layer labels nested with the current tag.

B. pageContex attribute: indicates the javax. servlet. jsp. PageContext object in the Web application.

3. before calling the doStartTag or doEndTag method, JSP containers call the setPageContext and setParent methods to set pageContext and parent. Therefore, you can directly access the pageContext variable in the tag processing class.

4. The pageContext member variable cannot be accessed in the TagSupport constructor, because the JSP Container has not yet called the setPageContext method to initialize pageContext.

5. TagSupport:

1. The TagSupport class provides two methods to process tags:

Public int doStartTag () throws JspException
Public int doEndTag () throws JspException

2. doStartTag: but when the JSP Container encounters the starting flag of the custom tag, it will call the doStartTag () method, and the doStartTag () method returns an integer to determine the subsequent process of the program.

A. Tag. SKIP_BODY: indicates that the code between the start and end labels is skipped.
B. Tag. EVAL_BODY_INCLUDE: indicates that the content between tags is executed normally.
C. Tag. EVAL_BODY_BUFFERED: parses the contained content.

3. doEndTag: however, if the JSP Container encounters the end mark of the custom tag, the doEndTag () method is called. The doEndTag () method also returns an integer to determine the subsequent process of the program.

A. Tag. SKIP_PAGE: indicates that the webpage is stopped immediately. Unprocessed static content and JSP programs on the webpage are ignored. Any existing output content is immediately returned to the client's browser.
B. Tag. EVAL_PAGE: indicates that the JSP page continues to be executed according to the normal process.

4. doAfterTag: Run in case of a TAG body

A. tag. EVAL_BODY_AGAIN; // if there are still objects in the collection, the TAG body is cyclically executed and the TAG body is processed cyclically (exists in javax. servlet. jsp. tagext. in the IterationTag Interface)
B. Tag. SKIP_BODY

6. Create tags containing fields:

1. Create a tag processor class FieldTag

package com.able.tag; import java.io.IOException; import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.TagSupport; public class FieldTag extends TagSupport {   private static final long serialVersionUID = 1540529069962423355L;     private String field;     private Integer count;   @Override  public int doEndTag() throws JspException {    try {      JspWriter out = pageContext.getOut();      out.print(field);      out.print(count);    } catch (IOException e) {      e.printStackTrace();    }    return super.doEndTag();  }     public String getField() {    return field;  }   public void setField(String field) {    this.field = field;  }   public Integer getCount() {    return count;  }   public void setCount(Integer count) {    this.count = count;  }  }

2. The tianjian tag in the tag. tld File

<Tag> <! -- Define the tag name --> <name> field </name> <! -- Define tag processing class --> <tag-class> com. able. tag. FieldTag </tag-class> <! -- Empty tag definition --> <body-content> empty </body-content> <attribute> <name> field </name> <required> true </required> <! -- Required value --> <rtexprvalue> true </rtexprvalue> <! -- Indicates whether jsp syntax, el language, or other dynamic languages are accepted, default Value: false --> </attribute> <name> count </name> <rtexprvalue> true </rtexprvalue> </attribute> </tag>

3. Define tags in jsp:

<Tm: field = "11" count = "22"/>

7. How to Create a tag processing class

1. introduce necessary resources

Import javax. servlet. jsp. *; import javax. servlet. http. *; import java. util. *; import java. io .*;
2. inherit the TagSupport class and overwrite the doStartTag ()/doEndTag () method

3. Obtain the java. util. Properties object from the ServletContext object.

4. Get the property value corresponding to the key from the Properties object

5. process the obtained attributes and output the results.

Create a Tag Library description file (Tag Library Descriptor)

1. The tag library description file, TLD for short, defines the user's tag library in XML format. The elements in a TLD file can be divided into three types:

A. Tag library elements
B. Tag Elements
C. Tag attribute Elements

2. The tag library element is used to set information about the tag library. Its common attributes include:

A. shortname: Specify the default prefix name (prefix) of the Tag Library );

B. uri: Set the unique access identifier of the Tag Library.

3. The tag element is used to define a tag. Its common attributes include:

A. name: Set the Tag name;

B. tagclass: Set the Tag processing class;

C. bodycontent: Set the body of the tag.

1) empty: indicates that there is no body in the tag;
2) JSP: JSP code can be added to the TAG body;
3) tagdependent: indicates that the content in the tag is processed by the tag itself.

4. The tag attribute element is used to define the attributes of a tag. Its common attributes include:

A. name: attribute name;
B. required: required or not. The default value is false;
C. rtexprvalue: whether the attribute value can be a request-time expression, which is similar to <% =... %>.

8. Use tags in Web Applications

1. If a custom JSP tag is used in a Web application, you must add an element to the web. xml file to declare the tag library where the referenced tag is located.

/Sometaglib
/WEB-INF/someTLD. tld

2. Set the unique identifier of the Tag Library and reference the Tag Libray in the Web application;

3. specify the location of the TLD file corresponding to the Tag Library;

4. Add <! -- Taglib %> command to declare a reference to the tag library.

5. prefix indicates the prefix when the Tag of the Tag Library is referenced in the JSP webpage. The uri is used to specify the Tag Library identifier, which must be consistent with the attributes in web. xml.

IX. case:

4. 1. Create a tag descriptor File

Create a *. tld tag descriptor file under the WEB-INF file: such

<Taglib>
<Tlibversion> 1.0 </tlibversion>
<Jspversion> 1.1 </jspversion>
<Shortname> eRedLab JSPTag Library </shortname>
<Uri>/testTag </uri>
<Info> test a custom tag </info>
<Tag>
<Name> hello </name>
<Tagclass> com. eredlab. taglib. test. TestTld </tagclass>
<Bodycontent> empty </bodycontent>
<Info> test a custom tag </info>
<Attribute>
<Name> begin </name>
<Required> true </required>
</Attribute>
<Attribute>
<Name> end </name>
<Required> true </required>
</Attribute>
</Tag>
</Taglib>

4. 2. Create a Tag Processor
/**
* @ Desc custom tag test class implements a simple Hello World tag
* @ Author Xia Zhongwei
* @ Version eRedLab 2007-9-10
*/
Public class TestTld extends TagSupport {
// Tag attribute begin
Private String begin = null;
// Label attribute end
Private String end = null;
// Constructor
Public TestTld (){

}

/* Initial Tag Method */
Public int doStartTag () throws JspTagException {
Return super. EVAL_BODY_INCLUDE;
}

/* Label end Method */
Public int doEndTag () throws JspTagException {
JspWriter out = pageContext. getOut ();
String sum = begin + end;
Try {
// Tag Return Value
Out. println (sum );
} Catch (IOException e ){
E. printStackTrace ();
}
Return super. SKIP_BODY;
}

/* Release resources */
Public void release (){
Super. release ();
}
/*************************************** *****
Attribute get () and set () Methods
**************************************** ***/
}

 

Load the tag descriptor file in Web. XML.
<! -- Load the tag descriptor file -->
<Taglib>
<Taglib-uri>/WEB-INF/test. tld </taglib-uri>
/WEB-INF/test. tld </taglib-location>
</Taglib>

. Use this tag in JSP
<% @ Taglib uri = "/testTag" prefix = "mytag" %>
<Mytag: hello end = "xia Zhongwei! "Begin =" custom tag output stream: Hello, "/>
<Mytag: hello end = "World! "Begin =" Hi, "/>
The WEB page output result is as follows:
Custom tag output stream: Hello, Xia Zhongwei! Hi, World!

Loop label body class: ForEach. java 1 import java. util. collection; 2 import java. util. iterator; 3 4 import javax. servlet. jsp. jspException; 5 import javax. servlet. jsp. tagext. bodyContent; 6 import javax. servlet. jsp. tagext. bodyTagSupport; 7 8 public class ForEach extends BodyTagSupport 9 {10 private String id; 11 private String collection; 12 private Iterator iter; 13 14 public void setCollection (String collection) 15 {16 this. Collection = collection; 17} 18 public void setId (String id) 19 {20 this. id = id; 21} 22 23 // run the 24 public int doStartTag () throws JspException25 {26 Collection coll = (Collection) pageContext. findAttribute (collection); 27 // indicates that if the specified collection is not found, the doEndTag () method is called directly without processing the TAG body. 28 if (coll = null | coll. isEmpty () return SKIP_BODY; 29 30 iter = coll. iterator (); 31 pageContext. setAttribute (id, iter. next (); 32 // indicates processing the label body in the existing output stream object, but bypassing the setBodyContent () and doInitBody () Methods 33 // The EVAL_BODY_INCLUDE must be returned here, otherwise, 34 return EVAL_BODY_INCLUDE; 35} 36 37 will not be displayed in the TAG body output on the webpage. // The content is executed before the doInitBody method, bypass and do not execute 38 @ Override39 public void setBodyContent (BodyContent arg0) 40 {41 System. out. println ("setBodyContent "); 42 super. setBodyContent (arg0); 43} 44 // This method is bypassed and will not be executed 45 @ Override46 public void doInitBody () throws JspException47 {48 System. out. println ("doInitBody"); 49 super. doInitBody (); 50} 51 52 // in case of a TAG body, execute 53 public int doAfterBody () throws JspException54 {55 if (iter. hasNext () 56 {57 pageContext. setAttribute (id, iter. next (); 58 return EVAL_BODY_AGAIN; // if there are still objects in the Set, the TAG body 59} 60 return SKIP_BODY is executed cyclically; // after the set is iterated, the TAG body is skipped, tune Use the doEndTag () method. 61} 62 63 // run 64 public int doEndTag () throws JspException65 {66 System. out. println ("doEndTag"); 67 return EVAL_PAGE; 68} 6970} Get VO Attribute Class: GetProperty. java 1 import java. lang. reflect. method; 2 3 import javax. servlet. jsp. jspException; 4 import javax. servlet. jsp. tagext. bodyTagSupport; 5 6 public class GetProperty extends BodyTagSupport 7 {8 9 private String name; 10 private String property; 1112 public vo Id setName (String name) 13 {14 this. name = name; 15} 1617 public void setProperty (String property) 18 {19 this. property = property; 20} 2122 @ SuppressWarnings ("unchecked") 23 public int doStartTag () throws JspException24 {25 try26 {27 Object obj = pageContext. findAttribute (name); 28 29 if (obj = null) return SKIP_BODY; 30 31 Class c = obj. getClass (); 32 // construct the GET method name get + attribute name (the first letter of the attribute name is capitalized) 33 String getMethodN Ame = "get" + property. substring (0, 1 ). toUpperCase () 34 + property. substring (1, property. length (); 35 Method getMethod = c. getMethod (getMethodName, new Class [] {}); 36 37 pageContext. getOut (). print (getMethod. invoke (obj); 38 System. out. print (property + ":" + getMethod. invoke (obj) + "t"); 39} catch (Exception e) 40 {41 e. printStackTrace (); 42} 43 return SKIP_BODY; 44} 4546 public int doEndTag () throws Js PException47 {48 return EVAL_PAGE; 49} 50} 5152 expressions directly access the static method in this class: ELFunction. java53public class ELFunction 54 {55 public static int add (int I, int j) 56 {57 return I + j; 58} 59} write a VO class for testing: UserVo. java 1 public class UserVo 2 {3 private String name; 4 private String password; 5 6 public String getName () 7 {8 return name; 9} 10 public void setName (String name) 11 {12 this. name = name; 13} 14 public String get Password () 15 {16 return password; 17} 18 public void setPassword (String password) 19 {20 this. password = password; 21} 22} created the TLD file tag. tld, placed in the WEB-INF directory 1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <taglib version = "2.0" 3 xmlns =" http://java.sun.com/xml/ns/j2ee "4 xmlns: xsi =" http://www.w3.org/2001/XMLSchema-instance "5 xmlns: shcemalocation =" http://java.sun.com/xml/ns/j2ee 6 http://java.sun.com/xml/ns/j2ee /Web-app_2_4.xsd "> 7 8 <description> custom tag </description> 9 <display-name> JSTL core </display-name> 10 <tlib-version> 1.1 </tlib -version> 11 <short-name> firstLabel </short-name> 12 <uri> http://java.sun.com/jsp/jstl/core </Uri> 1314 <! -- Create a custom iteration tag --> 15 <tag> 16 <name> forEach </name> 17 <tag-class> exercise. taglib. forEach </tag-class> 18 <! -- If there is no tag body, set empty, if there is a tag break, you must set JSP --> 19 <body-content> JSP </body-content> 20 <attribute> 21 <name> id </name> 22 <required> true </required> <! -- Identify whether the property is required --> 23 <rtexprvalue> true </rtexprvalue> <! -- Identifies whether attribute values can be used in Expression Language --> 24 </attribute> 25 <attribute> 26 <name> collection </name> 27 <required> true </required> 28 <rtexprvalue> true </rtexprvalue> 29 </attribute> 30 </tag> 3132 <! -- Create custom property tag --> 33 <tag> 34 <name> getProperty </name> 35 <tag-class> exercise. taglib. getProperty </tag-class> 36 <body-content> empty </body-content> 37 <attribute> 38 <name> name </name> 39 <required> true </ required> 40 <rtexprvalue> true </rtexprvalue> 41 </attribute> 42 <attribute> 43 <name> property </name> 44 <required> true </required> 45 <rtexprvalue> true </rtexprvalue> 46 </attribute> 47 </tag> 4849 <! -- Configure a function called by an expression --> 50 <function> 51 <name> add </name> <! -- Configure a tag and call it by referencing the prefix on the JSP page --> 52 <function-class> exercise. taglib. ELFunction </function-class> <! -- Implementation class --> 53 <function-signature> int add (int, int) </function-signature> <! -- Static Method: including the return type, method name, and input parameter type --> 54 </function> 55 </taglib>

Configure custom tags in the web. xml file

<Jsp-config> <taglib-uri> firstTag </taglib-uri> <taglib-location>/WEB-INF/tag. tld </taglib-location> </taglib> </jsp-config> use tags in jsp files. jsp <% @ page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib uri =" firstTag "prefix =" my "%> <jsp: useBean id =" userVo1 "class =" exercise. vo. userVo "scope =" request "> <jsp: setProperty name =" userVo1 "property =" name "value =" Hackiller "/> <jsp: setProperty name = "userVo1" property = "password" value = "123"/> </jsp: useBean> <jsp: useBean id = "uservo" class = "exercise. vo. userVo "scope =" request "> <jsp: setProperty name =" UserVo "property =" name "value =" YangYang "/> <jsp: setProperty name = "uservo" property = "password" value = "456"/> </jsp: useBean> <% List list = new ArrayList (); list. add (userVo1); list. add (uservo); pageContext. setAttribute ("voList", list); %> 

The above is a detailed description of all the content of the custom Taglib in jsp provided by xiaobian. I hope you can provide more support to the customer's home ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.