An introduction JSP tag library very detailed article, can be used as a reference manual

Source: Internet
Author: User
Tags empty expression getmessage sql variables string stmt string format
js| Reference | Reference manual

Standard JSP tags can invoke JavaBeans components or execute customer requests, which greatly reduces the complexity and maintenance of JSP development. JSP technology also allows you to customize taglib, in other words, taglib can be viewed as an extension of the JSP markup, just as XML is an extension of HTML. Taglib is usually defined in the tag tag library, where the tag stock is labeled with your own definition tag. In short, if you use Taglib, then you can design your own JSP tags!

In general, the custom tag tag is used primarily for manipulating hidden objects, processing HTML submission forms, accessing databases or other enterprise-class services, such as mail and directory operations, and so on. Custom tag tags are typically used by programmers who are proficient in the Java programming language and are familiar with data access and enterprise-class service access, allowing the HTML Designer to focus on web design without paying attention to the more complex business logic. At the same time, it also makes the library developer and the library user to carry on the reasonable division of labor, the custom tag label will those duplication work to encapsulate, thus greatly enhances the productivity, moreover may make the tag library can use in the different project, the perfect embodiment software reuse idea.

In this article, we mainly discuss:

· What is a custom tag tag?

· How do I use tag tag?

o Declare the tag library to use

o Find the tag handling class corresponding to the

o Tag Label type

· Custom Tag Label

o Tag Handling class

O Tag Library description

o Tag Tag Example

o tag with attributes

O with the body of the tag

o defines the tag for the script variable

o tag with a collaborative relationship

· Custom Tag Label

O An example of an iterative tag

o A template tag library

o how is the tag handling class actually called?


What is a custom tag?

A custom tag tag is a user-defined JSP tag. When a JSP page with a custom tag tag is compiled into a servlet by the JSP engine, the tag tag is transformed into an operation on an object called the tag-handling class. So when the JSP page is converted into a servlet by the JSP engine, the tag tag is actually transformed into the operation of the tag handler class.

The custom tag tag has many features, such as:

· You can customize the tag label properties in a JSP page

· Accessing all objects in a JSP page

· Can dynamically modify page output

· They can communicate with each other. You can create a JavaBeans component and then call this JavaBeans component in a tag and call it in another tag.

· Tag allows you to nest with each other, and you can perform some complex interactions in a JSP page.


Use 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, the 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 label, apply the JSP's Taglib designator to specify its tag library (note: Taglib to declare 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 TLD), which can be directly a TLD filename or a unique name. Prefix is a means of distinguishing between other TLD and tags with duplicate names in this TLD.

The TLD must be a. tld extension and stored in the currently applied Web-inf directory or its subdirectories. You can refer to it directly through its filename, or you can refer to it indirectly by other means.

The following taglib indicator refers directly to a TLD:

<%@ taglib uri= "/web-inf/tutorial-template.tld" prefix= "tt"%>

The following taglib indicator refers indirectly to a TLD through a logical name:

<%@ taglib uri= "/tutorial-template" prefix= "tt"%>

If you are referencing TLD indirectly, you must also define the mapping between this logical name and the TLD file in Web.xml by adding an element named Taglib to the Web.xml:

<taglib>

<taglib-uri>/tutorial-template</taglib-uri>

<taglib-location>

/web-inf/tutorial-template.tld

</taglib-location>

</taglib>


Implement this tag tag


In order to implement the tag tag, you have 2 ways to store the tag processing class. First, let the tag processing class in the manner of. Class in the current application of the Web-inf/class subdirectory, two, 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, which is the Tomcat/common/lib directory for Tomcat.


Tag Tag type


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

<tt:tag>

Body

</tt:tag>


A tag tag with no body is as follows:

<tt:tag/>


The simple tag tag

A tag tag without the body and attributes is as follows:

<tt:simple/>


Tag tag with attributes


Custom labels can have their own properties. Properties are generally defined in the start tag, and the syntax is attr= "value". A property acts as a parameter to a custom label, which affects the behavior of the tag handler class. You can define it in a TLD in detail.

You can assign a value to a property with a string constant, or you can assign a value to it 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 tag logic:iterate is to assign a value to an attribute using an expression:

<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 tab of struts, and if some labels define the properties of the parameter= "clear", 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 chose to clear the shopping cart!

</strong></font>

</logic:present>


In the end is the use of attributes or body to pass information?

As mentioned above, we can pass information either through attributes or through the body. In general, however, simpler types, such as strings or simple expressions, have the best use of attributes to pass information.


Tag tag that defines a script variable

A script variable refers to a variable or object that can be called in a JSP. It can be generated by the tag tag. The following example illustrates a tag tag that defines a transaction 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 tag with a collaborative relationship

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

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

<tt:tag2 attr1= "Obj1"/>

In the following example, if the outer tag tag creates an object, then all tag tags in the inner layer can use the object. Because the resulting object does not have a specified name, a conflict of fewer names can be created. This example illustrates a series of nested objects for collaboration.

<tt:outerTag>

<tt:innertag/>

</tt:outerTag>

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 its own JSP page containing the 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 processes required for different types of tag:

Method of tag handling class

Tag Tag type
The method that is called

Basic label
doStartTag, Doendtag, release

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

Tagged with content
doStartTag, Doendtag, release

Tagged with content, with content repeating loops
doStartTag, Doafterbody, Doendtag, release

Tagged with content, and content is interacting with JSP
doStartTag, Doendtag, release, Doinitbody, Doafterbody, release

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

If the tag tag is nested with each other, the tag handler class in the inner layer can access the upper tag handler class through its Parent property.

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


Tag library description (TLD for short)


Tag library is described in XML language, the TLD includes all tag tags in the tag library description, it is commonly used by the JSP server to verify the syntax of the tag is correct, or by the JSP developers to develop new tags.

The file name extension for the TLD must be. TLD and must be placed in the Web-inf directory or its subdirectories of the current Web application.

The start of the content of a TLD must follow the standard XML Start, which describes the DTD and XML versions, for example:

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

<! DOCTYPE taglib Public "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.2//en" "http://java.sun.com/dtd/ Web-jsptaglibrary_1_2.dtd">
The TLD must be a child element of the,<taglib> of its root element with <taglib> as follows:


Child elements of <taglib>

Element
Description

Tlib-version
version of the tag library

Jsp-version
The version of the JSP required by the tag library

Short-name
Mnemonics, an alias for tag (optional)

Uri
Used to determine a unique tag library

Display-name
Name used by the visualizer (such as JBuilder) to display (optional)

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

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

Description
Description of the tag library (optional)

Listener
See the following listener element

Tag
See tag element below

Listener element

A tag library may define classes as its event listening class, which is called the listener element in the TLD, and the JSP server instantiates the 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 will indicate its name, class name, script variable, Tag property. The value of the script variable can be obtained directly in the TLD or by the class that appends the information to the tag. Each property describes whether the attribute can be omitted, whether its value can be obtained by using 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
Describe

Name
Unique element name

Tag-class
Tag tags corresponding to the tag processing class

Tei-class
A subclass of Javax.servlet.jsp.tagext.TagExtraInfo that is used to express script variables (optional)

Body-content
Tag tag the type of body

Display-name
Name used by the visualizer (such as JBuilder) to display (optional)

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

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

Description
Description of this tag tag

Variable
Provides information for script variables (with Tei-class) (optional)

Attribute
Tag Tag's property name

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


The 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 invoked because the simple tag has no body, so this method returns Skip_body. When the JSP engine touches the end of the tag tag, Doendtag is invoked, and if the remaining pages are counted, it will return eval_page or it will return to Skip_page.

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


Public Simpletag extends TagSupport

{

public int doStartTag () throws Jspexception

{

try{

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 does not have content, you must define that the Body-content element is empty, for example

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


Tag tag with attributes


Tag Processing class

For each property of the tag tag, you must define its properties, as well as get and set methods, according to the JavaBeans specification. Take the logic:present label of struts for 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 handler 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 is not specified, the type of java.lang.String. If the Rtexprvalue element is defined as true or Yes, the return type of the attribute is defined in the type element.

<attribute>

<name>attr1</name>

<required>true|false|yes|no</required>

<rtexprvalue>true|false|yes|no</rtexprvalue>

The return type of the <type>attribute (only when Rtexprvalue is valid) </type>

</attribute>

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 <%= ...%>.

<tag>

<name>present</name>

<tag-class>org.apache.struts.taglib.logic.PresentTag</tag-class>

<body-content>JSP</body-content>

...

<attribute>

<name>parameter</name>

<required>false</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

...

</tag>


Validation of property elements


Valid values for the tag tag can be obtained from the description document in the tag library, and when the JSP page is compiled, the JSP engine is forced to refer to the rules defined in the TLD for checking.

There is also a way to validate the property element, which is to inherit the class Tagextrainfo first and then call its IsValid method. This class also plays a role in providing information about the script variables defined in tag.

The IsValid method passes the property information through the Tagdata object, which includes information about all the property names-values of the tag. Because the checksum occurs at run time, the value of this property is assigned to Tagdata.request_time_value.

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

<attribute>

<name>attr1</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>


This definition shows that ATTR1 can be assigned during run time.

The following IsValid method checks whether the value of the Attr1 property belongs to a Boolean type. Note that because ATTR1 can be assigned at run time, the IsValid method must check whether the tag user has a run-time assignment for this 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;

Else

return false;

}

Else

return true;

}

}

Tag with body

Tag Processing class


If the tag tag contains content, then the processing will be slightly different, but also depending on whether the tag processing class and body interaction. If you want to interact with the body, we think the tag processing class might want to manipulate the body.

The tag handler class does not interact with the body

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

If the tag processing class is to iterate over the body, it should implement Iterationtag or derive from the TagSupport. If the tag processing class thinks the body has not yet been computed, its doStartTag method and Doafterbody method must return to Eval_body_again.

The tag handler class interacts with the body

If the tag handler 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 wants to implement Doinitbody and Doafterbody method.

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 by 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 when the body content is already set, but is not evaluated. You can develop an initialization strategy based on different body content.

Doafterbody method

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

As with the doStartTag method, the Doafterbody method returns an indicator indicating whether the body is to continue to be computed, and if the calculation is to continue, Doafterbody should return eval_body_buffered, otherwise it should return skip_body.

Release method

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


The following example reads the contents of the body (which contains an SQL statement) and passes it to an object for querying. Because the body does not have to be recalculated here, Doafterbody will return to 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 ();

try{

Statement stmt = Connection.createstatement ();

Result result = Stmt.executequery (query);

}catch (SQLException e) {

throw new Jsptagexception ("Querytag:" + e.getmessage ());

return skip_body;

}

}


body-content element


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

<body-content>JSP|tagdependent</body-content>


If the contents of the body are custom or internal tag, script elements, or HTML extensive, then the classification is the JSP type. Other types, such as those described in the above code? D? d The type that passes the SQL statement class to query tag should be labeled Tagdependent.

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


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 Pagecontext.setattribute (Name,value,scope) or Pagecontext.setattribute (Name,value) methods. In general, the tag handler class gets it by the name of the script variable, which is generally available by the Get method.

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

The life cycle of an object (scope) is the following table:

The living table of the object

Name
Accessible scope
Life cycle

Page
Current page
Always works unless the page submits a response to the customer or redirects to a new page

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

Session
The current page or a page in the same browser window
Valid until the current browser, timeout, network failure is turned off

Application
All requests for the entire Web application
Valid until network failure, server failure

Provides information about script variables

The following example defines a script variable named "book" to access the information about 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>

</font>

When the JSP page that contains this tag is compiled, the JSP engine automatically generates the code for synchronization of this book (synchronization prevents several customers from accessing the book at the same time), and to generate 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

· Validity of this script variable

There are two ways to provide information about script variables to the JSP engine: Define the 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 it may reduce some flexibility.

Variable element

Variable elements are the following elements:

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

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

Name-given or Name-from-attribute must be selected, but the following child elements are optional:

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

· Declare? D? d This script variable refers to a new object, and 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 for script variables

Value
Effectiveness
Method

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

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

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

With struts as an 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. Take the bean:define tag as an example, you can define the following variable elements:

<tag>

<variable>

<name-from-attribute>id</name-from-attribute>

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

<declare>true</declare>

<scope>AT_BEGIN</scope>

</variable>

</tag>

Extra tag Information class

If you want to define an extra tag information class, you want to 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 name of the class to which the variable belongs

· Whether this variable refers to a new object

· Valid range for this variable

The JSP engine passes a parameter named data to the Getvariableinfo method, which includes all "property names" in the tag tag. D? D Property Value "Yes. It can be used to provide the name and class name of the script variable to the Variableinfo object.

Struts, for example, defines an additional tag information class named Definetei in the bean:define tag to provide information to script variables. Because of the script variable's name (book) and the class name (database. BookDetails) is passed through the tag tag's properties, which are generally defined in the Variableinfo build code and can be data.getattributestring to get the information. If you want to allow the book script variable to be available in the range from tag to 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"),

Type

True

Variableinfo.at_begin)

};

}

}


Note: The class name for the extra 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 the following:
<tei-class>
Org.apache.struts.taglib.bean.DefineTagTei
</tei-class>


Tag with a collaborative relationship


Tag through the sharing of objects to collaborate, JSP technology support 2 ways of object sharing.

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

The second way of sharing for the tag there is a nested relationship, the outer tag of the object created for the inner layer of the tag can be shared. The benefit of this form of sharing is that it reduces the likelihood of duplicate name conflicts.

To access an object created by a nested tag, the tag processing class must first find this nested tag object, using the TagSupport static method Tagsupport.findancestorwithclass (from, Class) or Tagsupport.getparent method. The former is used when it is not sure if 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, while dynamically created objects may be private objects of the parent class. Objects such as these can be saved using the SetValue method of the tag handling class, and are 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 the doStartTag. If the Connection property is set, the tag handler class obtains the connection object from the PageContext. Otherwise, the tag handler class first finds its parent tag handler class and then finds the connection object from its parent tag handler 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, use it.

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

}

Else

{

Connectiontag Ancestortag = (connectiontag) Findancestorwithclass (This,

Connectiontag.class);

if (Ancestortag = null)

{

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

}

Connection = Ancestortag.getconnection ();

}

}

}


The form of this query tag in the JSP page can be called from one 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:query>

Or

<tt:connection ...>

<x:query id= "Balances" >

SELECT account, balance from acct_table

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

</x:query>

</tt:connection>

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

<tag>

...

<attribute>

<name>connection</name>

<required>false</required>

</attribute>

</tag>



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.