Custom Taglib detailed _jsp programming in JSP

Source: Internet
Author: User
Tags tag name tld

Introduction of custom labels without parameter custom labels

1. Develop custom Label class

When we use a simple label on a JSP page, the bottom layer is actually supported by the tag processing class, which enables the team to better collaborate and develop (allowing the artist to participate in the development of JSP pages) by encapsulating complex functions using simple tags.

Custom label classes 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 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 page content.

The first is to introduce a label with no attributes for example: HelloWorld

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;}}}

Attention:

What is the difference between doStartTag and Doendtag in question 1:tagsupport
doStartTag is called when scanning to the start tag, Doendtag is called when scanning to the end tag.
such as:The JSP engine calls Dostrattag when parsing to

2, the establishment of TLD files

TLD is the abbreviation of Tag library definition, which is defined by tag libraries, the suffix of the file is TLD, each TLD file corresponds to a tag library, a tag library can contain multiple labels, and the TLD file is also called the tag library definition file.

The root element of a tag library definition file is taglib, which can contain multiple tag child elements, each of which has a label defined. Usually we can copy a tag library definition file under the Web container and modify it on this basis. Tomcat6.0, for example, contains a jsp2-example-taglib.tld file under the WEBAPPS\EXAMPLES\WEB-INF\JSP2 path, which is the tag library definition file for the demo.

Copy the file to the web-inf/path of the Web application, or to any subpath of the web-inf, and make a simple modification to the file, 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"

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 the label name-->

      <name>helloWorld</name>

      <!--definition label processing class-->

      <tag-class>org.lxh.taglib.HelloWorldTag</tag-class>

      <!-- Define label body as empty-->

      <body-content>empty</body-content>

    </tag>

</taglib>

Question 1: Why to use TagSupport and Bodytagsupport is the main difference is the label processing classes need 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 will read the contents of the label body and change the contents returned by the label body. The label implemented with TagSupport can be implemented with Bodytagsupport, because Bodytagsupport inherits TagSupport instead of implementing the Iterationtag interface, Because the Bodytagsupport inherits the TagSupport class, 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 each time to avoid the previous legacy data affecting the operation. Then determine if there is data to be processed, and if so, return eval_body_include to start processing the contents of the tag, if not, return eval_page skip the contents of the Label Execution tab below.

Doafterbody () method after each processing of the label inside the execution, to determine whether the loop has ended, if you can continue to cycle, return to Eval_body_again with a loop to get new data processing tags inside the content, if the loop end of the return Eval_page end tag.

Second, the custom JSP label processing process:

1. To introduce a tag library in a JSP:
2. Using tag library labels in your JSP
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 web.xml based on the URI property
5. Gets 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. To get the value of the corresponding element in a rounding element
9. The Web container creates an instance of the corresponding tag handle class based on the value of the element
The Web container calls the Dostarttag/doendtag method of this instance to complete the corresponding processing

Third, the basic steps to create and use a tag library:

1. Create label processing class (Tag Handler Class)
2. Create Tag library description file (tag Descrptor file)
3. Configure elements in the Web.xml file
4. Attracting tag libraries in JSP files

Iv. Introduction to 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: A processing class that represents an upper-level label that has nested current labels

B.pagecontex property: Represents a Javax.servlet.jsp.PageContext object in a Web application

The 3.JSP container invokes the Setpagecontext and SetParent methods before invoking the doStartTag or Doendtag method, setting PageContext and parent. So you can access PageContext variables directly in the label processing class

4. The PageContext member variable cannot be accessed in the TagSupport construction method because the JSP container has not called the Setpagecontext method to initialize the PageContext at this time

Five, the TagSupport processing label method:

The 1.TagSupport class provides two ways to process labels:

public int doStartTag () throws Jspexception
public int Doendtag () throws Jspexception

2.doStartTag: But the JSP container encounters the starting flag of a custom label, calls the doStartTag () method, and the doStartTag () method returns an integer value 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 between tags are properly executed
C.tag.eval_body_buffered: Parsing included content

3.doEndTag: The Doendtag () method is invoked when the JSP container encounters the end flag of a custom label. The Doendtag () method also returns an integer value to determine the program's subsequent process.

A.tag.skip_page: To stop the execution of Web pages immediately, static content on the Web page and JSP programs are ignored any existing output immediately returned to the customer's browser.
B.tag.eval_page: Indicates that the JSP Web page continues to execute in the normal process

4.doAfterTag: Encountered tag body execution

a.tag.eval_body_again;//If there is a pair of pixels in the collection, loop through the label body and loop the label body (existing in the Javax.servlet.jsp.tagext.IterationTag interface)
B.tag.skip_body

Create a label that contains a field:

1. Create 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;

 

  @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. In Tag.tld document Zhongtian Sword tag tag

<tag>

  <!--definition tag name-->

  <name>field</name>

  <!--defining label processing class-->

  < Tag-class>com.able.tag.fieldtag</tag-class>

  <!--defines the label body as an empty-->

  <body-content>empty </body-content>

  <attribute>

    <name>field</name>

    <required>true</ Required> <!--must be assigned 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>

3.jsp definition Label:

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

Vii. How to create a label processing class

1, the introduction of the necessary resources

Import javax.servlet.jsp.*; Import javax.servlet.http.*; Import java.util.*; Import java.io.*;
2. Inherit TagSupport class and Overwrite doStartTag ()/doendtag () method

3, get the Java.util.Properties object from the ServletContext object

4, from the properties of the object to obtain the corresponding value of the key

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

Create a tag library description file (tag libraries descriptor)

1, Tag library description file, referred to as TLD, the use of XML file format, defines the user's tag library. Elements in a TLD file can be grouped into 3 categories:

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

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

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

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

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

A.name: Set tag's name;

B.tagclass: Set tag of the processing class;

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

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

4, the label attribute element is used to define the properties 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 <%=...% >.

Use tags in web applications

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

/sometaglib
/web-inf/sometld.tld

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

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

4, in the JSP file needs to join the <!--taglib% > directives to declare the reference to the tag library.

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

Ix. Case:

4.1. Create a tag Descriptor file

Create the *.TLD tag descriptor file under the Web-inf file:

<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 a custom Label test class to implement a simple Hello World label
* @author Xia Chengwei
* @version Eredlab 2007-9-10
*/
public class Testtld extends tagsupport{
Label Property begin
Private String begin = null;
Label Property End
Private String end = null;
Constructors
Public Testtld () {

}

/* Label Initial method * *
public int doStartTag () throws jsptagexception{
Return super. Eval_body_include;
}

/* Tag 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 of resources * *
public void release () {
Super.release ();
}
/********************************************
Property Get (), set () method
*******************************************/
}

Load the tag 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 label in your JSP
<%@ taglib uri= "/testtag" prefix= "MyTag"%>
<mytag:hello end= "Xia Chengwei!" begin= custom Label output stream: Hello, "/>
<mytag:hello end= "world!" begin= "Hi,"/>
The results of the Web page output are as follows:
Custom Label output stream: Hello, Xia Chengwei! hi,world!

Circulation 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{private String ID;

One private String collection;

Private iterator ITER;

The public void Setcollection (String collection) {this.collection = collection;

The public void SetId (String id) {this.id = ID; 21} 22 23//Encountered start tag execution public int doStartTag () throws jspexception {Collection coll = (Collection)

Pagecontext.findattribute (collection);

27//means that if the specified collection is not found, then the Doendtag () method is called directly without handling the label body. if (coll==null| |

Coll.isempty ()) return skip_body;

iter = Coll.iterator ();

Pagecontext.setattribute (ID, Iter.next ()); 32//indicates that the label body is processed in the existing output stream object, but bypasses the Setbodycontent () and Doinitbody () method 33//Here must return eval_body_include, otherwise the label bodyContent will not be printed on the page shows the Eval_body_include;     35} 36 37//Before the Doinitbody method, which is bypassed here and does not perform the @Override-a-public void setbodycontent (bodycontent arg0) 40 {41

System.out.println ("Setbodycontent");

Super.setbodycontent (arg0); 43} 44//This method is bypassed and will not be executed @Override public void Doinitbody () throws Jspexception () System.out.println

("Doinitbody");

Super.doinitbody (); 50} 51 52//Encountered tab body execution of public int doafterbody () throws Jspexception () (Iter.hasnext ()) 56 {5

7 Pagecontext.setattribute (ID, Iter.next ());

eval_body_again;//return If there is a pair of pixels in the collection, the Loop Execution tab body, skip_body;//, iterates through the collection, skips the label body, and invokes the Doendtag () method.

61} 62 63//encounters the end tag execution of the Doendtag int () throws Jspexception () System.out.println ("Doendtag");

The return eval_page;

 68} 69 70} Get 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;

a private String property;

One public void SetName (String name) {this.name = name;

The public void SetProperty (String property) of This.property = property;

@SuppressWarnings ("Unchecked") is public int doStartTag () throws Jspexception {26 try {

Object obj = pagecontext.findattribute (name);

The IF (obj = null) return skip_body;

Class C = Obj.getclass (); 32//Construct get Method name get+ property name (first letter of property name) Getmethodname = "Get" + property.substring (0, 1). toUpperCase () 3

4 + property.substring (1, Property.length ());

Method GetMethod = C.getmethod (Getmethodname, New class[]{});

Pagecontext.getout (). Print (Getmethod.invoke (obj)); System.out.print (Property + ":" + getmethod.invoke (obj) + "T");

(d) catch (Exception e) {e.printstacktrace ();

Skip_body;

Doendtag public int () throws jspexception () Eval_page; 49} 50} 51 52 Expressions direct access to static methods in this class: Elfunction.java 53public class elfunction 54{public static int Add (int i,int J

) {i+j return;

 58} 59} Write a Test Vo class: Uservo.java 1public class Uservo 2{3 private String name;

 4 private String password;

 5 6 Public String GetName () 7 {8 return name;

9} public void SetName (String name) One {this.name = name;

The public String GetPassword () is password;

SetPassword public void (String password) {this.password = password; 21} 22} TLD file Tag.tld, placed in 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 Label </description> 9 <display-name>jstl core</display-name> 10 & Lt;tlib-version>1.1</tlib-version> <short-name>firstLabel</short-name> <uri>http ://java.sun.com/jsp/jstl/core</uri> <!--Create a custom iteration label--> <tag> <name>foreach</n Ame> <tag-class>exercise.taglib.ForEach</tag-class> <!--If there is no label body, set empty, if there is a label Hugh must set Jsp--&gt

; <body-content>JSP</body-content> <attribute> <name>id</name> <requir ed>true</required><!--Identify whether the attribute is mandatory--> <rtexprvalue>true</rtexprvalue><!-- Identify whether a property value can be in an expression language--> </attribute> <attribute> < <name>collection</name> Required>true</required> <rtExprvalue>true</rtexprvalue> </attribute> </tag> <!--Create a custom Get Property label--> <

Tag> <name>getProperty</name> <tag-class>exercise.taglib.GetProperty</tag-class> <body-content>empty</body-content> Panax Notoginseng <attribute> <re <name>name</name> quired>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribu te> <name>property</name> <required>true</required> &LT;RTEXPRVALUE&GT;TRUE&L

T;/rtexprvalue> </attribute> </tag> m <!--Configure a function called by an expression--> <function> <name>add</name><!--Configure a label to call--> <function-class>exercise.taglib.elfu via a reference prefix on the JSP page nction</function-class><!--Implementation Class--> <function-signature>int Add (int,int) </ function-signature><!--static method: Include return type, method name, the type of the parameter--> </function> 55</taglib> 

Configure a custom label in the Web.xml file

<jsp-config> <taglib> <taglib-uri>firstTag</taglib-uri> <taglib-location>/web-inf/ tag.tld</taglib-location> </taglib> </jsp-config> using tags in jsp files: tag.jsp <%@ page language= "Java "Import=" java.util.* "pageencoding=" Utf-8 "%> <%@ taglib uri=" Firsttag "prefix=" i "%> <jsp:usebean id=" use RVo1 "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= "UserVo2" class= "Exercise.vo.UserVo" scope= "request" > <jsp:setproperty name= "UserVo2" property= " Name "value=" Yangyang "/> <jsp:setproperty name=" userVo2 "property=" password "value=" 456 "/> </jsp:usebean

 > <% list = new ArrayList ();

 List.add (USERVO1);

 List.add (USERVO2);

Pagecontext.setattribute ("volist", list);
%>  

The above is a small series for everyone to bring the JSP custom taglib detailed content, I hope that we support cloud-Habitat Community ~

Related Article

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.