An introduction to the JSP tag library very detailed article

Source: Internet
Author: User
Tags string format tld

An introduction to JSP Tag Library very detailed article December 17, 2008 Wednesday 10:52

The standard JSP tag can invoke the JavaBeans component or execute the client's request, which greatly reduces the complexity and maintenance of JSP development.

JSP technology also allows you to customize the taglib, in other words, taglib can be seen as an extension of the JSP markup, just as XML is a

An extension of HTML. Taglib is usually defined in the tag tag library, which stores the tag tags you define yourself. In the case of Jane

If you use Taglib, then you can design your own JSP tags!
In general, custom tag tags are primarily used to manipulate hidden objects, handle HTML submission forms, Access databases, or other enterprise-class services

, such as mail and directory operations, and so on. Users of custom tag tags are generally proficient in the Java programming language, and the logarithm

Programmers who are very familiar with access and enterprise-level service access, for HTML designers, allow him to focus on the more complex

Business logic, and focus on web design. It also makes a logical division between library developers and library users, customizing tag tags

The duplication of work is encapsulated, which greatly increases productivity and enables the tag library to be used in different projects, to perfectly

The idea of software reuse is now in use.
In this article, we mainly discuss:
· What is a custom tag tag?
· How do I use tag tags?
o Declare the tag library to be used
o find the corresponding tag processing class
o type of tag tag
· Custom Tag Tags
o Tag Processing class
O Tag Library description
o Tag Tag Example
o tag with attributes
o tag with body
o defines the tag of the script variable
o the tag with a collaborative relationship
· Custom Tag Tags
O An example of an iterative tag
o A template tag library
o How is the tag processing class called?

What is a custom tag?
A custom tag tag is a user-defined JSP tag. When a JSP page containing a custom tag tag is compiled by the JSP engine

Into a servlet, the tag tag is transformed into an operation on an object called the tag processing class. So when the JSP page is turned by the JSP engine

As a servlet, the tag tag is actually transformed into the operation of the tag handler class.
Custom tag tags have many features, such as:
· You can customize the properties of the tag tag in the JSP page
· Access all objects in a JSP page
· Can dynamically modify page output
· This one can communicate with each other. You can create a JavaBeans component first, and then call this JavaBeans component in a tag,

It can also be called in another tag.
· Tag allows nesting of each other, and can do some complex interactions in a JSP page.

Using the tag tag

This section describes how to use tag tags in JSP pages and the different types of tag tags.
To use the tag tag, a JSP programmer must do 2 things:
· The tag library that declares this tag tag
· Implement this tag tag
The tag library where the tag tag is declared
If you want to use the tag tag, apply the JSP's Taglib indicator to specify its tag library (note: Taglib before using this tag tag

<%@ taglib uri= "/web-inf/tutorial-template.tld" prefix= "tt"%>
The URI attribute defines a unique tag library description (hereinafter referred to as the TLD), which can be directly a TLD file name or a unique name.

Prefix is a means of distinguishing between other TLDs and tags with duplicate names in this TLD.
The TLD must be extended with a. TLD and stored in the current app's Web-inf directory or its subdirectories. You can pass it by the file name straight

It can also be referenced indirectly in other ways.
The following taglib indicator directly refers to a TLD:
<%@ taglib uri= "/web-inf/tutorial-template.tld" prefix= "tt"%>
The following taglib indicator indirectly refers to a TLD by a logical name:
<%@ taglib uri= "/tutorial-template" prefix= "tt"%>
If you are indirectly referencing a TLD, you must also define the mapping between this logical name and the TLD file in Web. XML, as follows

Add an element named Taglib to Web. xml:

Implement this tag tag

To implement the tag tag, you have 2 ways to store the tag processing class. Let the tag processing class be stored in the current application in the. Class mode.

Web-inf/class Sub-directory, second, if the tag processing class is in the form of a jar package, it can be placed in the current application of the web-

Inf/lib directory, if the tag processing class is to be shared among multiple applications, it should be placed in the Common/lib directory on the JSP server

, for Tomcat, is the Tomcat/common/lib directory.

Tag Tag type

The custom tag tag follows the XML syntax. It has a start tag and an end tag, and some have body (that is, a text node):

A tag tag with no body is as follows:

A simple tag tag
A tag tag with no body and attributes is as follows:

Tag tag with attributes

Custom labels can have their own properties. Properties are generally defined in the opening tag, with the syntax attr= "value". The function of the property is quite

A parameter to a custom tag that affects the behavior of the tag processing class. You can define it in detail in the TLD.
You can assign a value to a property with a string constant, or it can be assigned a value by an expression, such as <%= ...%>. In struts, for example,

Its logic:present tag is a string constant used to assign a value to a property:
<loglic:present parameter = "Clear" >
Another label, Logic:iterate, is to use an expression to assign a value to a property:
<logci:iterate collection= "<%= bookdb.getbooks ()%>"
Id= "book" Type= "database. BookDetails ">

Tag tag with body
A custom label can contain other custom tags, script variables, HTML tags, or other content.
In the following example, this JSP page uses the logic:present tag of struts, if some tags define the parameter= "Clear"

's properties, the contents of the shopping cart are cleared, and a message is printed:
<logic:present parameter= "Clear" >
<% cart.clear (); %>
<font color= "#ff0000" size= "2" ><strong>
You have chosen to clear the shopping cart!

Does it use attributes or body to pass information?

As mentioned above, we can pass information either through attributes or through the body. In general, however, a simpler type, such as a string or a simple expression, is best used to pass information in a property.

Define tag tags for script variables

A script variable refers to a variable or object that can be called in a JSP. It can be generated by tag tags. The following example illustrates a tag tag that defines a transacted object named TX that is defined by Jndi. Script variables can be EJB objects, transactions, database connections, and so on:

<tt:lookup id= "TX" type= "UserTransaction" name= "Java:comp/usertransaction"/>

<% Tx.begin (); %>


Tag tags with collaborative relationships

You can collaborate by sharing objects between custom tag tags. In the following example, the label TAG1 creates an object named Obj1, which can still be reused in the label Tag2.

<tt:tag1 attr1= "obj1" value1= "value"/>

<tt:tag2 attr1= "Obj1"/>

In the following example, if the tag tag of the outer layer creates an object, then all tag tags in the inner layers can use this object. Since the resulting object does not have a specified name, it is possible to have a conflict with fewer names. This example illustrates a series of collaborative nested objects.




Tag Processing class

The tag processing class must implement either the tag interface or the Bodytag interface, but it is now generally popular to inherit from the TagSupport or Bodytagsupport classes, which can be found in the Javax.servlet.jsp.tagext package.

When the JSP engine sees that its JSP page contains a tag tag, it calls the doStartTag method to handle the beginning of the tag tag and calls the Doendtag method to handle the end of the tag tag.

The following table describes the different processing procedures required for different types of tags:

Method of tag handling class

Tag Tag type
The method that is called

Basic label
doStartTag, Doendtag, release

Labels with attributes
doStartTag, Doendtag, set/getattribute1 ... N, Release

Tagged with content
doStartTag, Doendtag, release

Label with content, and content repeats the loop
doStartTag, Doafterbody, Doendtag, release

Tagged with content, and the content interacts with the JSP
doStartTag, Doendtag, release, Doinitbody, Doafterbody, release

A tag processing class can interact with the JSP through Javax.servlet.jsp.PageContext, and through the Javax.servlet.jsp.PageContext class, the tag processing class can access the request in the JSP, The session and application to the image.

If the tag tag is nested with each other, the tag processing class in the inner layer can access the tag processing class on the upper level through its parent property.

In general, all tag processing classes are made into jar packages for easy release.

Tag library description (TLD)

The tag library is described in the XML language, and the TLD includes a description of all tag tags in the tag library, which is typically used by the JSP server to verify the correctness of the tag, or to be used by JSP developers to develop new tags.

The TLD must have a. tld file name extension and must be placed in the Web-inf directory or its subdirectories of the current web App.

The beginning of the content of a TLD must conform to the standard XML beginning, which describes the version of the DTD and XML, for example:

<?xml version= "1.0" encoding= "Iso-8859-1"?>

<! DOCTYPE taglib Public "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.2//en" " Web-jsptaglibrary_1_2.dtd ">
The TLD must take <taglib> as its root element,,<taglib>, as a sub-element of the following table:

Child elements of <taglib>


Version of Tag Library

The version of the JSP required by the tag library

Mnemonic, an alias for tag (optional)

Used to determine a unique tag library

The name used by the visualizer (such as JBuilder) to display (optional)

Small icon (optional) to be displayed by a visualizer (such as JBuilder)

A large icon (optional) to be displayed by a visualizer (such as JBuilder)

Description of the tag library (optional)

See listener element below

See tag element below

Listener elements

A tag library may define classes as its event-listening classes, which are referred to as listener elements in the TLD, and the JSP server instantiates these listening classes and registers them. The listener element has a child element called Listener-class, and the value of this element must be the full class name of the listening class.

Tag element

Each tag element in the tag library should indicate its name, class name, script variable, Tag property. Where the value of a script variable can be defined directly in the TLD or through a class of tag-attached information. Each property describes whether this property can be omitted, whether its value can be obtained through JSP syntax such as <%= ...%>, and the type of the property.

Each tag corresponds to a tag element in the TLD, and the following table is the child element of the tag element:

Child elements of the tag element

Element name

A unique element name

Tag processing class for tags tag

Subclass of Javax.servlet.jsp.tagext.TagExtraInfo, which is used to express script variables (optional)

Type of tag tag body

The name used by the visualizer (such as JBuilder) to display (optional)

Small icon (optional) to be displayed by a visualizer (such as JBuilder)

A large icon (optional) to be displayed by a visualizer (such as JBuilder)

Description of this tag tag

Provides information about script variables (same as Tei-class) (optional)

Property name of Tag tag

The following sections describe how to implement them specifically for different types of tags.

A simple tag

Tag Processing class

The simple tag processing class must implement the doStartTag and Doendtag methods of the tag interface. When the JSP engine touches the beginning of the tag tag, doStartTag is called because the simple tag does not have a BODY, so this method returns Skip_body. When the JSP engine touches the end of the tag tag, Doendtag is called, and if the remaining page is to be computed, it will return eval_page, otherwise it will return skip_page.

Here is an example: for the label <tt:simple/>, its tag processing class is implemented as follows:

Public Simpletag extends TagSupport


public int doStartTag () throws Jspexception



Pagecontext.getout (). Print ("Hello.");

}catch (Exception e) {

throw new Jsptagexception ("Simpletag:" E.getmessage ());


return skip_body;


public int Doendtag ()


return eval_page;



Note: If the tag tag has no content, you must define the Body-content element as empty, for example


Tag tag with attributes

Tag Processing class

For each property of the tag tag, you must define its properties according to the JavaBeans specification, along with the get and set methods. Take Struts's Logic:present label as an example,

<logic:present parameter= "Clear" >

Accordingly, this tag processing class should have the following methods and definitions:

protected String parameter = NULL;

Public String GetParameter ()


return this.parameter;


public void Setparameter (String parameter)


This.parameter = parameter;


Note: If your property name is ID and your tag processing class inherits from the TagSupport class, you do not need to define its properties and set and get methods, because they have already been defined in TagSupport.

Attribute elements

For each property of the tag tag, you must define whether it is necessary, whether its value can be obtained with an expression such as <%= ...%>, and its type (optional), and if it does not specify its type, it is implicitly considered to be a java.lang.String type. If the Rtexprvalue element is defined as true or Yes, the return type of attribute is defined in the type element.





<type>attribute return type (only valid when Rtexprvalue is true) </type>


If a property of tag is not required, the tag processing class automatically provides a default value.

For example, a property called parameter is defined in the tag tag of logic:present, but it is not required, and it can be assigned by an expression such as <%= ...%>.













Validation of property elements

Valid values for tag tags can be obtained from the tag library's documentation, and when the JSP page is compiled, the JSP engine is forced to check against the rules defined in the TLD.

There is also a way to verify the property element, which is to inherit the class Tagextrainfo first and then call its IsValid method. This class also serves as a function of providing the script variable information defined in the tag.

The IsValid method passes the property information through the Tagdata object, which includes all of the tag's property name-value information. Because the checksum occurs at run time, the value of this property is assigned a value of Tagdata.request_time_value.

For example, the tag tag <tt:twa attr1= "value1"/> defined in the TLD as follows:






This definition shows that the ATTR1 can be assigned during operation.

The following IsValid method checks whether the value of the Attr1 property belongs to a Boolean type. Note that since the ATTR1 can be assigned at run-time, the IsValid method must check whether the tag user has assigned a runtime value to the tag.

public class Twatei extends Tagextrainfo


public boolean isValid (Tagdata data)


Object o = Data.getattribute ("attr1");

If (o! = null && o! = tagdata.request_time_value)


if ((String) O). toLowerCase (). Equals ("true") | |

(String) O). toLowerCase (). Equals ("false"))

return true;


return false;



return true;



Tag with body

Tag Processing class

If the tag tag contains content, it will be handled slightly differently, depending on whether the tag handles the class to interact with the body. If you want to interact with the body, we think the tag processing class might want to manipulate the body.

Tag processing class does not interact with body

If the tag processing class does not interact with the body, the tag processing class should implement the tag interface or derive from TagSupport, and if the body is to be computed, then the doStartTag method should return eval_body_include, otherwise it should return skip_body.

If the tag processing class is to be iterated over the body, it should implement Iterationtag or derive from TagSupport. If the tag processing class thinks the BODY is not finished, then its doStartTag method and Doafterbody method must return Eval_body_again.

Tag handler class interacts with body

If the tag processing class interacts with the body, the tag processing class should implement the Bodytag interface or derive from the Bodytagsupport. This kind of tag processing class generally implements the Doinitbody and Doafterbody methods.

The body allows some methods to read and write its contents. The tag processing class can invoke the GetString or Getreader method of the body content to extract information from the body, and also use the Writeout (out) method to write the contents of the body to the out object. The Out object is obtained through the Getpreviousout method of the tag processing class.

If the contents of the BODY need to be computed, then the doStartTag method must return eval_body_buffered, otherwise it will return skip_body.

Doinitbody method

This method is called before the body content is already set, but is not evaluated. You can create an initialization strategy based on different body content.

Doafterbody method

This method is called after the body content has been evaluated.

As with the doStartTag method, the Doafterbody method returns an indicator indicating whether to continue the calculation of the BODY, or doafterbody should return eval_body_buffered if it is to continue, otherwise it should return skip_body.

Release method

The tag handler class calls this method to reset its state to its initial state, and frees all private resources.

The following example reads the contents of the body (which contains an SQL statement) and then passes it to an object for querying. Because the BODY does not have to be recalculated here, Doafterbody returns Skip_body.

public class Querytag extends Bodytagsupport


public int doafterbody () throws Jsptagexception


bodycontent BC = getbodycontent ();

Extracts the body's contents in a string format

String query = bc.getstring ();

Clear Body

Bc.clearbody ();


Statement stmt = Connection.createstatement ();

result = stmt.executequery (query);

}catch (SQLException e) {

throw new Jsptagexception ("Querytag:" E.getmessage ());

return skip_body;



Body-content elements

Since tag may have body, you must use the Body-content element to specify the type of the body content:


If the body content is custom or internal tag, script element, or HTML wide, it is categorized as a JSP type. Other types, such as those described in the above code? D? d The type of SQL statement class passed to query tag should be labeled Tagdependent.

Note: In fact, the value of body-content does not affect the handling of the body content of the tag processing class, it is only used by the tag editing tool to describe the body content.

Define script variables with tags

Tag Processing class

The tag processing class is responsible for creating or setting script variables defined in the page, implemented using the Pagecontext.setattribute (Name,value,scope) or Pagecontext.setattribute (Name,value) method. In general, the tag processing class gets it by the name of the script variable, and the name of the script variable is generally obtained using the Get method.

If the value of a script variable depends on an object in the context of the tag processing class, it can use the Pagecontext.getattribute (Name,scope) method to find the object. The general process is that the tag handler first finds the script variable, processes it, and then sets its new value using the Pagecontext.setattribute (Name,object) method.

The lifetime of the object (scope) is the following table:

The life table of the object

Accessible scopes
Life cycle

Current page
remains in effect unless the page submits a response to the customer or redirects to a new page

The page to which the current page or current page is redirected
Always works unless the page submits a response to the customer

The current page or a page in the same browser window
remains in effect unless the current browser is closed, timeout, network failure

All requests for the entire Web application
remains in effect unless a network failure occurs, a server failure

Provides information about the script variable

The following example defines a script variable named "book" To access information about the books in the program:

<bean:define id= "book" Name= "Bookdb" property= "bookdetails" type= "database. BookDetails "/>

<font color= "Red" size= "2" >

<%= messages.getstring ("cartremoved")%>

<strong><jsp:getproperty name= "book" property= "title"/></strong>


When the JSP page containing this tag is compiled, the JSP engine automatically generates the code for synchronization of this book (synchronization avoids the conflicts caused by several clients accessing the book at the same time), and to generate the synchronization code, the JSP engine needs to know the following information about this script variable:

· Script variable Name

· The class to which the script variable belongs

· Whether this script variable refers to a new or existing object

· The validity of this script variable

There are two ways to provide information about a script variable to the JSP engine: Define a variable child element in the TLD, or define an additional tag information class with the Tei-class child element. Using variable is the simplest, but may reduce some flexibility.

Variable elements

Variable elements are like the following elements:

· Name-given? D? D gives the name, is a constant

· Name-from-attribute? D? D property name, name of the property given at compile time

Name-given or Name-from-attribute must select one, but the following sub-elements are optional:

· Variable-class? D? The type of the D variable, which defaults to java.lang.String.

· Declare? D? D If this script variable refers to a new object, the default is true.

· Scope? D? The scope of the D script variable, which defaults to nested. The following table describes several types of scope:

Valid range of script variables


Between the start and end of the tag tag
If the tag processing class implements the Bodytag interface, it is called in Doinitbody and doafterbody, otherwise it is called in doStartTag

From the beginning of the tag tag to the end of the page
If the tag processing class implements the Bodytag interface, it is called in Doinitbody, Doafterbody, and Doendtag, otherwise it is called in doStartTag and Doendtag

From the end of the tag tag to the end of the page
Called in Doendtag

In struts, for example, the implementation of its bean:define tag follows the JSP1.1 specification, which requires the use of additional tag information classes to define script variables. The variable element is added to the JSP1.2 specification. With the bean:define tag as an example, you can define the following variable elements:




<variable-class>database. Bookdetails</variable-class>





Additional tag Information class

If you want to define an additional tag information class, you will inherit the Javax.servlet.jsp.TagExtraInfo class. A Tagextrainfo class must implement the Getvariableinfo method, which returns an array class called Variableinfo, which includes the following information:

· Variable name

· The class name to which the variable belongs

· Whether this variable refers to a new object

· Valid range of this variable

The JSP engine passes a parameter named data to the Getvariableinfo method, including all the attribute names in the tag tag in data. D? D attribute value "pair. It can be used to provide the name and class name of the script variable to the Variableinfo object.

In struts, for example, it defines an additional tag information class named Definetei in the bean:define tag to provide information to script variables. Because of the name of the script variable (book) and the class name (database. BookDetails) is passed through the properties of tag tags, which are generally defined in Variableinfo's build code and are available data.getattributestring methods to obtain this information. If you want to allow the book script variable to be available from the start of the tag until the end of the entire JSP page, its scope should be set to At_begin. As shown below:

public class Definetei extends Tagextrainfo


Public variableinfo[] Getvariableinfo (tagdata data)


String type = data.getattributestring ("type");

If (type = = NULL)

Type = "Java.lang.Object";

return new variableinfo[] {

New Variableinfo (data.getattributestring ("id"),







Note: The class name for the additional tag information class must be defined in the Tei-class child element under the tag tag in the TLD. Therefore, the definition in Definetei's tei-class looks like this:

Tag with a collaborative relationship

Tag uses shared objects to collaborate, and JSP technology supports 2 ways of sharing objects.

The first approach is to share objects using the PageContext object (which supports sharing between JSP pages and tag-processing classes), and if you want to invoke an object created by another tag-processing class in a tag-processing class, you can call Pagecontext.getattribute ( Name, scope) method.

The second way of sharing is for the tag between the nested relationship, the outer tag created by the object for the inner layer of the tag can be shared. The benefit of this form of sharing is that it reduces the likelihood of conflicting duplicate names.

To access an object created by a nested tag, the tag processing class must first find the nested tag object, using the static method of the TagSupport Tagsupport.findancestorwithclass (from, Class) or Tagsupport.getparent method. The former is used when it is not determined whether this tag is a nested tag object. Once its parent class is found, it can access all of its dynamically or statically created objects. Statically created objects are members of the parent class, and dynamically created objects may be private objects of the parent class. Such objects can be stored using the SetValue method of the tag processing class, which is obtained using the GetValue method.

The following example illustrates the two methods of sharing objects. In this example, a query tag checks whether a property name named Connection is set in doStartTag. If the Connection property is set, the tag handler class obtains the connection object from the PageContext. Otherwise, this tag-processing class finds its parent tag-processing class first, and then finds the connection object from its parent tag-processing class.

public class Querytag extends Bodytagsupport


Private String ConnectionID;

public int doStartTag () throws Jspexception


String cid = getconnection ();

if (CID! = null)


There is a connection ID that uses it.

Connection = (connection) pagecontext.getattribute (CID);




Connectiontag Ancestortag = (connectiontag) Findancestorwithclass (This,


if (Ancestortag = = null)


throw new Jsptagexception ("A query label that has no connection attribute must be nested by a connection tag.") ”);


Connection = Ancestortag.getconnection ();




This query label can be called in a JSP page in any of the following 2 definitions:

<tt:connection id= "Con01" ...> ... </tt:connection>

<tt:query id= "Balances" connection= "Con01" >

SELECT account, balance from acct_table

where customer_num = <%= Request.getcustno ()%>



<tt:connection ...>

<x:query id= "Balances" >

SELECT account, balance from acct_table

where customer_num = <%= Request.getcustno ()%>



At the same time, the connection attribute must be specified in the TLD to be optional and defined as follows:








An introduction to the JSP tag library very detailed 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: 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.