Custom Taglib in JSP

Source: Internet
Author: User
Tags tld

First, custom tags get started without parameters custom labels

1. Developing a custom Label class
When we use a simple tag on a JSP page, the underlying is actually supported by the label processing class, which allows for the use of simple tags to encapsulate complex functionality, allowing the team to better collaborate on development (allowing artists to better participate in the development of JSP pages).
Custom label classes must inherit a parent class: Javax.servlet.jsp.tagext.SimpleTagSupport, or TagSupport In addition, the JSP custom label class has the following requirements.

If the Label class contains attributes, each property has a corresponding getter and setter method.
Override the Dotag () or doStartTag () or Doendtag () method method, which is responsible for generating the page content.
First of all, it is a label without attributes with HelloWorld as an example:

The Java code is as follows:

public class Helloworldtag extends TagSupport {private static final long serialversionuid = -3382691015235241708l; @Overri depublic 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;}} @Overridepublic 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;}}

Attention:

What is the difference between doStartTag and Doendtag in the question 1:tagsupport?
doStartTag is called when scanning to the start tag, and Doendtag is called when scanning to the end tag.
For example:The JSP engine parses to

2. tld file
TLD is the abbreviation for Tag library definition, which is the tag database definitions, the suffix of the file is TLD, each TLD file corresponds to a tag library, a tag library can contain multiple tags, and a TLD file is also known as a tag library definition file. The root element of the
Tag library definition file is taglib, which can contain more than one tag child element, each of which defines a label. Usually we can copy a tag library definition file under the Web container and modify it on this basis. For example Tomcat6.0, a Jsp2-example-taglib.tld file is included under the WEBAPPS\EXAMPLES\WEB-INF\JSP2 path, which is the tag library definition file for the demonstration.
Copy the file to the Web app's web-inf/path, or any web-inf of the file, and make a simple modification to it, with the modified Helloworld.tld file code 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 label--><tag><!--define a label name-- <name>helloWorld</name><!--defining label handling classes--><tag-class>org.lxh.taglib.helloworldtag</ tag-class><!--define the label body as empty--><body-content>empty</body-content></tag></taglib>

Question 1: Why to use TagSupport and bodytagsupport difference is mainly the label processing class whether to interact with the tag body, if you do not need to interact with the TagSupport, otherwise use Bodytagsupport.

Interaction is whether the label processing class reads the contents of the tag body and changes the content returned by the tag body. With TagSupport implementation of the label, can be implemented with Bodytagsupport, because Bodytagsupport inherited tagsupport and not to implement the Iterationtag interface, Because Bodytagsupport inherits the TagSupport class, and the class already implements the Iterationtag interface and implements the functionality.

The doStartTag () method executes at the beginning of the label, remembering that the class is initialized every time, avoiding the effect of the last remaining data on the operation. Then determine if there is data to be processed, if there is, then return eval_body_include start processing the contents of the label, if not, return eval_page skip the label content to execute the contents of the tag.

The Doafterbody () method executes after each processing of the contents of the label, determines whether the loop has ended, and if it can continue to loop, returns Eval_body_again with the loop to get new data to process the inner contents of the label again, and returns the Eval_page end tag if the loop ends.

Second, the custom JSP tag processing process:

1. Introduction of Tag libraries in JSPs:
2. Using tag library tags in JSPs
3. The Web container obtains the URI attribute value of the taglib declared in the first step, based on the prefix in the second step
4. The Web container finds the corresponding element in XML based on the URI attribute
5. Get the value of the corresponding element from the element
6. The Web container finds the corresponding. tld file from the web-inf/directory based on the value of the element
7. Find the element corresponding to tagname from the. tld file
8. Gets the value of the corresponding element in the
9. The Web container creates an instance of the corresponding tag handle class based on the value of the element
The Web container calls this instance of the Dostarttag/doendtag method to complete the corresponding processing

Iii. basic steps for creating and using a tag library:
1. Create the label's processing class (Tag Handler Class)
2. Create tag library profile (tag libraries Descrptor file)
3. Configuring elements in the Web. xml file
4. Attracting tag libraries in JSP files

Iv. introduction of TagSupport class:

1. The class that handles the label must extend the Javax.servlet.jsp.TagSupport.

Main properties of the 2.TagSupport class:

A.parent property: Represents a processing class that is nested with the upper label of the current label

B.pagecontex property: Represents a Javax.servlet.jsp.PageContext object in a web App

3.JSP container before calling the doStartTag or Doendtag method, the Setpagecontext and SetParent methods are called first, and the PageContext and the parent are set. Therefore, the PageContext variable can be accessed directly in the label 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 the PageContext.

Five, TagSupport processing label method:

The 1.TagSupport class provides two ways to handle labels:
public int doStartTag () throws Jspexception
public int Doendtag () throws Jspexception
2.doStartTag: But the JSP container encounters the start flag of the custom label, it calls the doStartTag () method, and the doStartTag () method returns an integer value used to determine the subsequent process of the program.
A.tag.skip_body: Indicates that the code between the start and end tags has been skipped
B.tag.eval_body_include: Indicates that the contents of the label are executed normally
C.tag.eval_body_buffered: Parsing the included content
3.doEndTag: But the JSP container encounters the end flag of the custom label, it calls the Doendtag () method. The Doendtag () method also returns an integer value used to determine the program's subsequent process.
A.tag.skip_page: To stop the execution of the Web page immediately, the non-processed static content on the webpage and the JSP program are ignored any existing output content is immediately returned to the customer's browser.
B.tag.eval_page: Indicates that the JSP Web page continues to execute according to normal process
4.doAfterTag: Encountered tag body execution
a.tag.eval_body_again;//If there is a pair of images in the collection, the loop executes the label body, loops over the label body, (exists in the Javax.servlet.jsp.tagext.IterationTag interface)
B.tag.skip_body

VI. Create a label that contains a field:

1. Create a label 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;@ overridepublic 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. In Tag.tld file Transit Sword tag tag

  <tag><!--define label name--><name>field</name><!--define label handling class--><tag-class> com.able.tag.fieldtag</tag-class><!--define the label body as empty--><body-content>empty</body-content>< Attribute><name>field</name><required>true</required> <!--Whether it is necessary to assign a value-->< rtexprvalue>true</rtexprvalue><!--Indicates whether to accept JSP syntax or El language or other dynamic language, default false--></attribute>< attribute><name>count</name><rtexprvalue>true</rtexprvalue></attribute></ Tag>

tags defined in 3.jsp:

<tm:field field= "One" count= "one"/>

Vii. How to create a label processing class

1. Introduction of 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. Get the Java.util.Properties object from the ServletContext object

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

5, the corresponding processing of the acquired properties and output results

Create Tag library profile (Tag libraries descriptor)

1, Tag library description file, referred to as TLD, using XML file format, defines the user's tag library. The elements in a TLD file can be divided into 3 categories:

A. Tag library elements
B. Label elements
C. Tag attribute Element

2, Tag library elements used to set the tag library related information, its common properties are:

A.shortname: Specifies the default prefix name (prefix) of the tag library;

B.uri: Sets the unique access identifier for the tag library.

3, the label element is used to define a label, its common properties are:

A.name: Set the name of the tag;

B.tagclass: Set the processing class of tag;

C.bodycontent: Sets the body (body) content of the label.

1) Empty: Indicates that there is no body in the label;
2) JSP: The body of the tag can be added to the JSP program code;
3) Tagdependent: Indicates that the contents of the tag are handled by the label itself.

4. The tag attribute element is used to define the property of the label, and its common properties are:

A.name: attribute name;
B.required: property is required, default is false;
C.rtexprvalue: Whether the property value can be an request-time expression, that is, an expression similar to <%=...% >.

Viii. using tags in Web applications

1. If a custom JSP tag is used in the Web application, you must include the element in the XML. file, which declares the tag library where the referenced label is located

/sometaglib
/web-inf/sometld.tld

2, set the tag library unique identifier, in the Web application will be based on it to reference tag Libray;

3. Specify the location of the TLD file corresponding to the tag library;

4, in the JSP file need to join <!--taglib% > directive to declare a reference to the tag library.

5. prefix represents the prefix used to refer to this tag library's label in a JSP Web page, which specifies the identifier of the tag libraries, which must be consistent with the attributes in Web. Xml.

Nine, Case:

4.1. Create a Label descriptor file
Create the *.TLD tag descriptor file under the Web-inf file: such as
<taglib>
<tlibversion>1.0</tlibversion
<jspversion>1.1</jspversion>
<shortname>eredlab Jsptag library</shortname>
<uri>/testtag</uri>
<info> custom Label test </info>
<tag>
<name>hello </name>
<tagclass>com.eredlab.taglib.test.testtld</tagclass>
<bodycontent>empty </bodycontent>
<info> custom Label test </info>
<attribute>
<name>begin</name
<required>true</required>
</attribute>
<attribute>
<name>end </name>
<required>true</required>
</attribute>
</tag>
</taglib

4.2. Create a label processor
/**
* @desc Custom Label test class to implement a simple Hello World tag
* @author Xia Chengwei
* @version Eredlab 2007-9-10
*/
public class Testtld extends tagsupport{
Tag Properties begin
Private String begin = null;
Label Property End
Private String end = null;
constructor function
Public Testtld () {

}

/* Tag Initial 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{
The return value of the label
OUT.PRINTLN (sum);
}catch (IOException e) {
E.printstacktrace ();
}
Return super. Skip_body;
}

/* Release Resources */
public void release () {
Super.release ();
}
/********************************************
Property Get (), set () method
*******************************************/
}

The

Loads the label descriptor file in Web. Xml.
<!--load tag descriptor file-->
<taglib>
<taglib-uri>/web-inf/test.tld</taglib-uri>
< Taglib-location>/web-inf/test.tld</taglib-location>
</taglib>
5.2. Use this tag in a JSP
<%@ Taglib uri= "/testtag" prefix= "MyTag"%>
<mytag:hello end= "Xia Chengwei!" begin= "custom label output stream: Hello,"/>
<mytag: Hello end= "world!" begin= "Hi,"/>
Web page output results are as follows:
Custom Label output stream: Hello, Xia Chengwei! hi,world!

Circulating label Body class: Foreach.java 1import java.util.Collection; 2import Java.util.Iterator; 3 4import javax.servlet.jsp.JspException; 5import javax.servlet.jsp.tagext.BodyContent; 6import Javax.servlet.jsp.tagext.BodyTagSupport;  7 8public class ForEach extends Bodytagsupport 9{10 private string id;11 private string collection;12 private Iterator iter;13 public void Setcollection (String collection), {this.collection = collection;17}18 public void set ID (String ID): {this.id = id;21}22 23//Encounters start tag Execution of public int doStartTag () throws JspException25 {Coll ection coll = (Collection) pagecontext.findattribute (Collection); 27//indicates that if the specified collection is not found, the label body is not processed and the Doendtag () method is called directly. if (coll==null| |    Coll.isempty ()) return skip_body;29 to ITER = Coll.iterator (); Pagecontext.setattribute (ID, Iter.next ()); 32 Indicates that the label body is processed in an existing output stream object, but bypasses Setbodycontent () and Doinitbody () method 33//This must be returned to Eval_body_include, otherwise the contents of the tag body will not be output on the Web page show return E Val_body_include;35}36 37//in DoinitbodyThe method is executed before, where it is bypassed not to perform the @Override39 public void setbodycontent (Bodycontent arg0) (Setbodycontent System.out.println  "); Super.setbodycontent (arg0); 43}44//This method is bypassed and will not be executed @Override46 public void Doinitbody () throws JspException47 {System.out.println ("doinitbody"); Super.doinitbody (); 50}51 52//Encounter tag body execute a public int doafterbody () throw S JspException54 {iter.hasnext ()) Pagecontext.setattribute (ID, Iter.next ()), Eval_b ody_again;//If there is an alignment in the collection, the loop executes the label body}60 return skip_body;//iterates over the collection, skips the label body, and calls the Doendtag () method.  61}62 63//encounters an end tag to perform a public int doendtag () throws JspException65 {System.out.println ("Doendtag"); Eval_page;68}6970} Gets the VO attribute class: Getproperty.java 1import Java.lang.reflect.Method; 2 3import javax.servlet.jsp.JspException; 4import Javax.servlet.jsp.tagext.BodyTagSupport; 5 6public class GetProperty extends Bodytagsupport 7{8 9 private string name;10 private string property;1112 public vo ID SETname (string name) THIS.name = name;15}1617 public void SetProperty (string property) * {This.property       = property;20}2122 @SuppressWarnings ("unchecked") all public int doStartTag () throws JspException24 {try26 {27  Object obj = pagecontext.findattribute (name); if (obj = = null) return skip_body;30 Class c = Obj.getclass (); 32//Construct get Method name get+ property name (property name first letter capitalized) String getmethodname = "Get" + property.substring (0, 1) . toUpperCase () + property.substring (1, Property.length ()); Method GetMethod = C.get Method (Getmethodname, New class[]{}), PNs pagecontext.getout (). Print (Getmethod.invoke (obj)); Print (Property + ":" + getmethod.invoke (obj) + "T"), "Exception" catch (E) 42 {e.printstacktrace ();}4 3 return skip_body;44}4546 public int Doendtag () throws JspException47 {return eval_page;49}50}5152 expression directly accessing this static method in class: Elfunction.java53public class elfunction 54{55 public static int Add (int i,int j) 1pub (i+j;58}59} write a Test Vo class: Uservo.java Lic class Uservo 2{3 private string name; 4 private string password; 5 6 public string GetName () 7 {8 return NA Me 9}10 public void SetName (string name) one {this.name = name;13}14 public String GetPassword () password;17}18 public void SetPassword (String password) {This.password = password;21}22} build the TLD file Tag.tld, put it in W Eb-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/ Java EE 6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> 7 8 <description> Custom Tags </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>13 <!--Create a custom iteration label-->15 <tag>16 <name>foreach</ Name>17 <tag-class>exercise.taglib.foreach</tag-class>18 <!--If there is no label body, set empty, if there is a label Hugh must be set jsp-- >19 <body-content>jsp</body-content>20 <attribute>21 <name>id</name>22 < required>true</required><!--whether the identity attribute is required-->23 <rtexprvalue>true</rtexprvalue><!-- Identifies whether a property value can be-->24 in an expression language </attribute>25 <attribute>26 <name>collection</name>27 <require d>true</required>28 <rtexprvalue>true</rtexprvalue>29 </attribute>30 </tag>31 32 <!--Create custom Get property tags-->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>48 <!--Configure a function called by an expression-->50 <function>51 <name>add</name><!--Configure a label in the JSP The page invokes-->52 <function-class>exercise.taglib.ELFunction</function-class><!--implementation Class-->53 by reference prefixes &L T;function-signature>int Add (int,int) </function-signature><!--static method: Includes the return type, method name, type of the entry parameter-->54 </ Function>55</taglib>

Configure custom labels in the Web. xml file

1<jsp-config>2 <taglib>3 <taglib-uri>firsttag</taglib-uri>4 <taglib-location>/ Web-inf/tag.tld</taglib-location>5 </taglib>6</jsp-config> using tags in jsp files: tag.jsp 1<%@ page Language= "java" import= "java.util.*" pageencoding= "Utf-8"%> 2<%@ taglib uri= "Firsttag" prefix= "my"%> 3 4< Jsp:usebean id= "UserVo1" class= "Exercise.vo.UserVo" scope= "Request" > 5 <jsp:setproperty name= "UserVo1" property = "Name" value= "Hackiller"/> 6 <jsp:setproperty name= "userVo1" property= "password" value= "123"/> 7</jsp: Usebean> 8 9<jsp:usebean id= "UserVo2" class= "Exercise.vo.UserVo" scope= "request" &GT;10 <jsp:setproperty name = "UserVo2" property= "name" value= "Yangyang"/>11 <jsp:setproperty name= "UserVo2" property= "password" value= "456 "/>12</jsp:usebean>1314<%15 List List = new ArrayList (); List.add (USERVO1); List.add (USERVO2); 18 Pagecontext.setattribute ("volist", list); 19%>2021

Custom Taglib in JSP

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.