[Reserved] Deepen Taglib

xiaoxiao2021-03-06  107

In general, custom TAG tags are mainly used to operate hidden objects, process HTML submission forms, access databases or other enterprise-class services, such as email and directory operations, and more. Users who custom TAG tags are generally those who are very proficient in Java programming languages, and are very familiar with data access and enterprise-level service access. For HTML designers, they can't pay attention to those more complicated. Business logic, and put energy on web design. At the same time, it also makes a reasonable division of labor in library developers and library users, and customizes TAG tags to encapsulate those repetitive work, which greatly improves productivity, and makes the Tag library can be used in different projects, perfectly embodied software. Reuse thinking.

In this article, we are mainly discussed:

· What is a custom TAG tag?

· How to use TAG tag?

o Statemon the Tag library to use

o Find the TAG processing class with it

o TAG tag type

· Customized TAG tag

o TAG processing class

o Tag library description

o TAG label example

o Tag with property

o Tag with body

o Defines the Tag of the script variable

o TAG with collaborative relationship

· Customized TAG tag

o An an iterative tag example

o a template Tag library

o TAG handling class how to call?

What is a custom TAG?

A custom TAG tag is a JSP tag defined by a user. When a JSP page containing a custom TAG tag is compiled into a servlet by the JSP engine, the TAG tag is converted to an operation to a target called a TAG processing class. Then when the JSP page is converted to servlet by the JSP engine, the TAG tag is actually converted to the TAG processing class.

Customized TAG tags have many features, such as:

· You can customize the properties of the TAG tag in the JSP page

· Access all objects in the JSP page

· You can dynamically modify the page output

· This can communicate with each other. You can create a JavaBeans component first, then call this JavaBeans component in a TAG, and you can call it in another TAG.

· TAG allows each other to complete some complex interactions in a JSP page.

Use the TAG tag

This section mainly describes how to use TAG tags in the JSP page, as well as different types of TAG tags.

To use a TAG tag, JSP programmers must do 2 things:

· Declare this Tag label TAG library

· Realize this TAG tag

Declare Tag Label location

If you want to use a TAG tag, apply JSP's Taglib indicator to specify its Tag library (Note: taglib is notice before using this tag tag)

<% @ Taglib URI = "/ Web-INF / TUTORIAL-TEMPLATE.TLD" prefix = "TT"%>

The URI attribute defines a unique label description (hereinafter referred to as TLD), which can be directly a TLD file name or a unique name. Prefix is ​​a means used to distinguish other TLDs and the TAG having a rename in this TLD.

TLD must be used as an extension, and stored in the currently applying web-inflicid or its subdirectory. You can directly reference it through its file name, or you can indirectly by other ways.

The following taglib indicator directly references a TLD:

<% @ Taglib URI = "/ Web-INF / TUTORIAL-TEMPLATE.TLD" prefix = "TT"%>

The following Taglib indicator is indirectly referenced by a logical name:

<% @ Taglib Uri = "/ Tutorial-Template" prefix = "TT"%>

If it is indirectly reference TLD, then you must also define this logical name between this logical name and TLD file in Web.xml, which is to add a taglib in Web.xml:

/ tutorial-template

/Web-inf/tutorial-template.tld

Realize this TAG tag

In order to implement TAG tags, you have two ways to store TAG processing classes. First, let the TAG handle class in a .CLASS manner in the current application's web-inf / class subdirectory, two, if the tag processing class exists in the form of a JAR package, that can be placed on the current application Web-INF Under the / lib directory, if the TAG handling class is shared in multiple applications, then it should be placed in the common / lib directory on the JSP server. For Tomcat, it is the Tomcat / Common / Lib directory.

TAG tag type

Customized TAG tags follow XML syntax. It has a start tag and an end tag, some there is a body (ie text node):

Body

A Tag tag without bodyy is as follows:

Simple TAG tag

A Tag tag without body and attributes is as follows:

Tag tag with attributes

Custom labels can have their own properties. Attributes are generally defined in the start tag, the syntax is attr = "value". The role of the property is equivalent to a parameter of the custom label, which affects the behavior of the TAG processing class. You can define it in TLD.

You can use a String constant to assign a value, or you can assign it by expressions, such as <% = ...%>. Take Struts as an example, its logic: Present tag is used by String constants to assign attributes:

And another tag logic: iTerate is assigned to attributes with expressions:

ID = "book" type = "database.bookdetails">

Tag tag with body

A custom label can contain other custom labels, script variables, HTML tags, or other content.

In the following example, this JSP page uses Struts's logic: present tab, if some tags define the properties of Parameter = "Clear", will clear the contents of the shopping cart, then print a message:

<% Cart.clear ();%>

You have chosen to clear your cart!

Do you use the attribute or use body to deliver information?

As mentioned above, we can pass information throughout the property, or by body. However, in general, relatively simple types, such as strings or simple expressions are best adopted to pass information.

The so-called script variable defining the script variable is a variable or object that can be called in the JSP. It can be generated by a Tag tag. The following example illustrates a TAG tag that defines a transaction processing object defined by JNDI named TX. Script variables can be EJB objects, transactions, database connections, etc.

<% Tx.begin ();%>

...

Tag tag with collaborative relationship

Customized TAG tags can be achieved by sharing objects. In the following example, the label tag1 creates an object called OBJ1, and OBJ can still be reused in the label TAG2.

In the following example, if the outer TAG tag creates an object, all TAG tags in the inner layer can use this object. Because there is no specified name, you can conflict with less researchers. This example explains a series of collaborative nested objects.

TAG processing class

The TAG handling class must implement a TAG interface or a BodyTag interface, but now inherit from the Tagsupport or BodyTagSupport class, these classes or interfaces can be found in the javax.servlet.jsp.tagext package.

When the JSP engine sees that there is a TAG tag in your JSP page, it calls the dostartTAG method to handle the beginning of the TAG tag, call the DOENDTAG method to handle the end of the TAG tag.

The following table shows that different types of TAG require different processing:

TAG handling class

TAG tag type

Method called

Basic label

Dostarttag, Doendtag, Release

Label with property

DostartTag, Doendtag, Set / GetAttribute1 ... N, Release

Label with content

Dostarttag, Doendtag, Release

Tags with content,

Content repeat cycle

DostartTag, DoafterBody, Doendtag, Release

Tags with content, and interact with JSP

Dostarttag, Doendtag, Release, DoinitBody, DoafterBody, Release

A Tag handling class can interact with JSP via javax.servlet.jsp.pageContext, through the Javax.Servlet.jsp.PageContext class, TAG processing classes can access Request, Session, and Application Optics in JSP.

If the Tag tag is nesting, the inner tag processing class can access the upper TAG processing classes through its Parent attribute.

All TAG processing classes are generally packets to be released.

Tag library description (TLD)

The Tag library is described in XML language. TLD includes a description of all TAG tags in the TAG library, which is generally used by the JSP server to verify the syntax correctness of the TAG, or by JSP developers to develop new labels.

The TLD file extension must be .TLD, and must be placed in a Web-INF directory or its subdirectory of the current web application.

The beginning of a TLD must comply with the standard XML start, used to describe the version of DTD and XML, for example:

TLD must be used as its root element, the child elements of are as follows:

child elements

ELEMENT

Description

TLIB-VERSION

Tag library version

JSP-Version

JSP version required by the Tag library

Short-name

A helper, one alias of tag (optional)

URI

Used to determine a unique TAG library

DISPLAY-NAME

Name (optional) used by visual tools (such as jbuilder) (optional)

Small-icon

Small icons used to display visual tools (such as jbuilder) (optional)

Large-icon

Big icons used by visualization tools (such as jbuilder) (optional)

Description

Description of Tag libraries (optional)

Listener

See the Listener element below

Tag

See the TAG element below

Listener element

A Tag library may define some classes as its event listening class, which are called Listener elements in TLD, and the JSP server will instantiate these listening classes and register them. There is a child element called Listener-Class in the Listener element, and the value of this element must be the full class of the listening class.

TAG element

Each TAG element must pointed out its name, class name, script variable, and tag properties in the Tag library. Where the value of the script variable can be obtained directly in the TLD or through the class of TAG additional information. Each attribute describes whether this property can be omitted, whether it can be obtained by <% = ...%>, and the type of attributes.

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

Child elements of tag elements

Element name

description

Name

Unique element name

Tag-class

TAG tag corresponding to TAG processing classes

Tei-Class

Javax.Servlet.jsp.tagext.tagextrainfo subclass for expressing script variables (optional)

Body-Content

TAG Tags Body type

DISPLAY-NAME

Name (optional) used by visual tools (such as jbuilder) (optional)

Small-icon

Small icons used to display visual tools (such as jbuilder) (optional)

Large-icon

Big icons used by visualization tools (such as jbuilder) (optional)

Description

Description of this TAG tag

Variable

Provide information on script variables (with Tei-Class) (optional)

Attribute

Tag label attribute name

The following sections describe how different TAGs are implemented specifically.

Simple TAG

TAG processing class

Simple TAG Handling Class must implement the DostartTAG and DOENDTAG methods for the TAG interface. When the JSP engine encounters the beginning of the TAG tag, the dostartTAG is called because the simple TAG has no body, so this method will return Skip_Body. When the JSP engine encounters the end of the TAG tag, DOENDTAG is called, and if the remaining page is still calculated, it will return EVAL_PAGE, otherwise Skip_page will be returned. The following is an example: For the label , its TAG processing class is implemented as follows:

Public SimpleTag Extends Tagsupport

{

Public int desartTAG () THROWS JSPEXCEPTION

{

Try {

PageContext.get (). Print ("Hello.");

} catch (exception e) {

Throw new JSptagexception ("SimpleTag:" E.getMessage ());

}

Return Skip_body;

}

Public int doendtag ()

{

Return Eval_page;

}

}

Note: If there is no content in the Tag tag, it must define the body-content element empty, for example

EMPTY

Tag tag with attributes

TAG processing class

For each property of the Tag tag, you must define its properties in accordance with the JavaBeans specification, as well as GET and SET methods. As an example of Struts's Logic: Present tag,

Correspondingly, 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 is called ID, and your tag handling class is inherited from the TagSupport class, then you do not need to define its properties and set and get methods because they have already defined in tagsupport.

Attribute element

For each property of the Tag tag, you must define if it must be, it can be obtained by expressions such as <% = ...%>, and its type (optional), if not specifying its type Then, the default is 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.

attr1

True | False | Yes | NO

TRUE | FALSE | YES | NO

Attribute return type (only when RTEXPRVALUE is really valid)

If a property of tag is not a must, the TAG handling class automatically provides a default.

For example, in the Logic: Present this Tag tag defines a property called parameter, but it is not a must, and it can be assigned by an expression such as <% = ...%>.

present

org.apache.struts.taglib.logic.presentttag

JSP

...

parameter

false

TRUE

...

Attribute element check

Valid values ​​for TAG tags can be obtained from the tag library documentation, and when the JSP page is compiled, the JSP engine will enforce the rules defined in the TLD.

There is also a method to perform a verification of attribute elements, just inherit the class TAGEXTRAINFO, then call it IsValid method. This class also plays a role in providing script variable information defined in tag.

The isvalid method passes the property information through the TagData object, which includes information of all of the property name-value of the TAG. Since the calibration occurs at runtime, the value of this attribute will be assigned to tagdata.Request_time_Value.

For example, a TAG tag is defined in TLD as follows:

attr1

True

TRUE

This definition describes that ATTR1 can be assigned during operation.

The following IsValid method checks if the value of the Attr1 property belongs to the Boolean type. Note that because Attr1 can be assigned at runtime, the isvalid method must check if the TAG user is assigned to 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) .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, the processing mode will be slightly different, and it is also necessary to depend on whether the TAG processing class is interacting with the Body. If you want to interact with Body, we think that the TAG handling class must be able to operate Body.

TAG processing class is not interacting with Body

If the Tag processing class is not interacting with the Body, the TAG handling class should implement a TAG interface or derive from tagsupport. If Body is to be calculated, then the dostartTAG method should return Eval_Body_include, otherwise you should return Skip_Body.

If the TAG processing class is repeated to the body, it should implement iTerationTAG or derive from Tagsupport. If the TAG handling class thinks that the body has not been calculated, its DostartTAG method and the DoafterBody method must return Eval_Body_again.

TAG handling class interact with Body

If the Tag handling class interacts with the Body, the TAG processing class should implement the Bodytag interface or derive from the Bodytagsupport. This TAG handling class typically wants the DoinitBody and DOAFTERBODY methods.

Body allows some methods to read and write it. The TAG handling class can call the GetString or getReader method of the body content to extract information from the body, or Writeout (OUT) method can be written to the OUT object. The OUT object is obtained by a getPreviOUSOUT method for TAG processing.

If the content of the body needs to be calculated, the dostartTAG method must return Eval_Body_buffered, otherwise it will return Skip_Body.

DOINITBODY method

This method has been set in the Body content, but is not called before. You can develop initialization policies based on different BODY content.

DoafterBody method

This method is called after the Body content has been calculated.

Like the DOSTARTTAG method, the DoafterBody method returns an indicator indicating whether you want to continue calculating the body, if you want to continue the calculation, DoafterBody should return Eval_Body_buffered, otherwise it should return Skip_Body.

RELEASE method

Tag processing class calls this method to reset its state into an initial state and release all private resources.

The following example reads the content of the body (which contains a SQL statement), then passes it to an object, let it query. Since Body here is not required to be recalculated, DoafterBody will return Skip_Body.

Public Class Querytag Extends Bodytagsupport

{

Public int dressboDy () THROWS JSptagexception

{

Bodycontent bc = getBodyContent ();

// Put the content of the body 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 a body, you must use the body-content element to specify the type of body content:

JSP | tagdependnt

If the content of the body is a custom or internal TAG, script elements, or HTML, it is classified as JSP type. Other types, such as the above code? D? D Pass the SQL Statement class to Query Tag should be labeled as TagDependent.

Note: The value of the body-content does not affect the processing of the TAG handling class to the body content, which is only used by the TAG editing tool to describe the content of this Body.

Define script variables with tags

TAG processing class

The TAG handling class is responsible for creating or setting the script variables defined in the page, implemented with PageContext.SetAttribute (Name, Value, Scope) or PageContext.settribute (Name, Value) method. In general, the TAG handling the class through the name of the script variable, the name of the script variable is usually available to the GET method.

If the value of the script variable depends on an object in the context in the TAG processing class, it can be found in the PageContext.getaTribute (Name, Scope) method. The general processing process is a TAG handling class to find a script variable, and then processes it, and then use the method of pageContext.setTribute (Name, Object) to set its new value.

The survival period of the object is as follows:

Object survival cycle table

first name

Accessibility

Survival cycle

page

The current page

Has been valid, unless the page is submitted or redirected to a new page to the customer

REQUEST

Current page or current page redirected page

Have been effective, unless the page is submitted to customers

session

Current page or page in the same browser window

Always valid, unless the current browser is closed, timeout, network failure

Application

All requests for the entire web application

Always valid unless a network failure occurs, server failure

Provide information about script variables

The following example defines a script variable called "BOOK" to access information about books in the program:

<% = Messages.getstring ("Cartremoved")%>

When the JSP page containing this TAG is compiled, the JSP engine automatically generates synchronous code about this book (synchronization can avoid conflicts caused by several customers to access this book), to generate synchronization code, JSP engine needs to know this Script variables are as follows:

· Script variable name

· The class belonging to the script variable

· Does this script variable reference 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 a Variable child element in TLD, or define an additional TAG information class with a TEI-Class sub-element. The easiest use of Variable, but may reduce some flexibility.

Variable element

Variable elements are as follows:

· Name-given? D? D The name given is a constant

· Name-from-Attribute? D? D attribute name, the name given during compile

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

· Variable-Class? D? D variable type, default is java.lang.string.

· DECLARE? D? D This script variable quoted a new object, default is true.

· Scope? D? D script variable range, default is NESTED. The following table describes several types of Scope:

Valid range of script variables

value

Validity

method

Nested

Between the beginning and end of the TAG tag

If the TAG handling class implements the BodyTag interface, call at_begin in DONITBODY and DOAFTERBODY.

From the beginning of the TAG label, until the end of the page

If the TAG handling class implements the BodyTag interface, call in DOINITBODY, DOAFTERBODY, and DOENDTAG, otherwise call in DostartTAG and DOENDTAG

AT_END

From the end of the TAG tag, until the end of the page

Call in DoendTag

Take Struts as an example, its Bean: Define tag implementation follows the JSP1.1 specification, this specification requires the use of additional TAG information classes to define script variables. The Variable element is joined in the JSP1.2 specification. Take the bean: Define tag as an example, you can define the following Variable element:

ID >>

Database.bookDetails

True

AT_BEGIN

Additional TAG information class

If you want to define an additional TAG information class, you have to inherit the javax.servlet.jsp.tagextrainfo class. A TAGEXTRAINFO class must implement a GetVariableInfo method. This method returns a class class name called VariableInfo, which includes the following information:

· variable name

· Class name to variables

· Does this variable reference a new object

· Effective range of this variable

The JSP engine passes a parameter named DATA to the getVariableInfo method, including all "property names? D? D attribute values" in the Tag tab in the data. It can be used to provide the name and class name of the script variable to the VariableInfo object.

Take Struts as an example, which defines an additional TAG information class named DEFINETEI in the Bean: Define tag to provide information to the script variable. Since the name of the script variable (BOOKASE.BOOKDETAILS) is passed through the property of the Tag tag, they typically define in the VariableInfo build code and can be used to get this information. If the Book script variable can be used in the range from Tag until the end of the JSP page, it should be set to at_begin. As follows:

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.GetaTRibuteString ("ID"),

TYPE,

True,

VariableInfo.at_begin)

}

}

}

Note: About the class name of the additional TAG information class must be defined in the TEI-Class sub-element under the TAG tag in TLD. Therefore, definitions in Definetei's Tei-Class look like this:

Org.apache.struts.taglib.bean.definetagtei

TAG with collaborative relationship

TAG is collaborated by sharing objects, and JSP technology supports two ways of object sharing.

The first method is to use the PageContext object to share the sharing of objects (can support sharing between JSP pages and TAG processing classes), if you want to call objects created by another TAG processing class in a TAG processing class, PageContext can be called. GetAttribute (Name, Scope) method.

The sharing of the second mode is that the object created by the outer TAG is common to the TAG of the inner layer for a nested relationship between TAG. The benefits of this form of sharing are reduced the possible researchers.

To access a nested TAG created, the TAG handling class must first find this Nested TAG object, available Tagsupport's 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 dynamic or static creation. Static created objects are members of the parent class, while dynamically created objects may be the private object of the parent class. Objects such as this can be saved with the setValue method of the TAG to process and is obtained with the getValue method.

The following examples describe the methods of the above two shared objects. In this example, a query tag checks if a property name named Connection is set in DostartTag. If the Connection property is set, the TAG handling class gets this Connection object from pageContext. Otherwise, this Tag handling class first finds its parent TAG handling class, then find the Connection object from its parent tag processing class.

Public Class Querytag Extends Bodytagsupport

{

Private string connectionId;

Public int desartTAG () THROWS JSPEXCEPTION

{

String CID = getConnection ();

IF (CID! = NULL)

{

// There is a Connection ID and use it.

Connection = (Connection) PageContext.getaTRibute (CID);

}

Else

{

ConnectionTag AncestortAg = (ConnectionTag) FindanceStorwithClass (this,

ConnectionTag.class;

IF (AncestortAg == NULL)

{

Throw new JSptagexception ("A query tab without the Connection property must be nested by a Connection tag.");

}

Connection = AncestortAg.getConnection ();

}

}

}

This query tag can be selected from the following two definitions in the JSP page:

...

SELECT Account, Balance from Acct_Table

Where customer_num = <% = Request.getCustNo ()%>

or

SELECT Account, Balance from Acct_Table

Where customer_num = <% = Request.getCustNo ()%>

At the same time, you must specify the connection attribute in TLD as an optional, defined as follows:

...

Connection

false

转载请注明原文地址:https://www.9cbs.com/read-98230.html

New Post(0)