Taglib

xiaoxiao2021-03-05  30

[Author: smltiger Source: Java Research Organization]

Summary: Standard JSP tags can call 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 fact, Taglib can be seen as an extension of JSP tags, as XML is an extension of HTML. Taglib is typically defined in the Tag tag library, which puts your own defined tag tag. In short, if you use taglib, then you can design your JSP tag! 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 Declare that the Tag library to find the TAG handling class o tag tag type? Custom TAG Tag O TAG Handling Class O Tag Library Description O TAG Tag Example O with Property Tago with Body Tago defines the script Tago TAGO TAG with a collaborative relationship? Custom TAG Tag O An Iterative TAG Example O A Template Tag Library O TAG Processing Class How is it called? 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:? Can you customize the property of the TAG tag in the JSP page? Access all objects in the JSP page? 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. Using Tag Tags This section mainly describes how to use TAG tags in the JSP page, as well as different types of TAG tags. To use the TAG tag, the JSP programmer must do 2 things:? Declare the Tag library of this TAG tag? Implement this TAG tag declares that the tag library where the Tag tag is located If you want to use the TAG tag, apply JSP TagLib indicators to specify its Tag library (Note: taglib wants to declare a unique label library description in the <% @ Taglib URI = "/ Web-INF / TAGLIB URI =" / Web-INF / TAGLIB URI = "/ Web-INF / TAGLIB URI =" / Web-INF / TAGLIB URI = "/ Web-INF / TTORIB URI =" (Hereinafter referred to as TLD), it can be 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 indicators directly reference 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 you are indirect reference TLD, then you must also define the mapping between this logical name and TLD file in Web.xml, the specific practice is Add an element called Taglib in Web.xml: / tutorial-template /web-inf/tutorial-template.tld Implement this TAG Tag To implement a TAG tag, 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 tag follows XML syntax. It has a start tag and an end tag, some there is a body (ie text node): body A Tag tag without a body is as follows: simple Tag Tags A tag tag without body and attributes is as follows: Tag tag Custom Tags with Properties You can have your 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 a value: and another tab logic: Itereate is assigned to attribute assignments: Tag Tags with Body You can include 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! Is it to deliver information with the properties or use body? 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 custom TAG tags with collaborative relationships 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, then all of its inner layer This object can be used with the Tag tag. Because there is no specified name, you can conflict with less researchers. This example explains a series of collaborative nested objects. TAG Processing class TAG handling class must implement TAG interface or bodytag interface, but now inherit from Tagsupport or BodyTagSupport classes, 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 need different processing procedures: TAG processing class method TAG tag type called method Basic tag DOSTARTTAG, DOENDTAG, Release with property tag DOSTARTTAG, DOENDTAG, SET / GETATTRIBUTE1 ... N, RELEASE Tags DOSTARTTAG, DOENDTAG, RELEASE Take content Tags, DOEENDTAG, Release DostartTag, DoafterBody, Doendtag, Release Triendal Tags, And JSP Interactions DOSTAG, DOEENDTAG, Release, DoinitBody, DoeFterBody, Release A Tag processing class You can use Javax.Servlet.jsp.PageContext to interact with JSP, through the Javax.Servlet.jsp.PageContext class, TAG handling classes can access Request, Session, and Application objects 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) Tag library is described in XML language, and TLD includes a description of all TAG tags in the TAG library. It is generally used by the JSP server to verify the syntax correctness of the TAG, or by JSP developers Used 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 content 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 ElementDescriptionTlib-VersionTag library version JSP version of the JSP version of the JSP version of the JSP version short-name Help, TAG an alias (optional) URI for use Determine a unique Tag library Display-name by a visualization tool (such as jbuilder) (optional) Small-icon is visualized by a small icon (optional) LARGE-ICON is visualized Tools (such as JBuilder) DEVRIPTION DESCRIPTION Description of the Tag Library (Optional) Listener See the listener element TAG See the tag element listner element A tag library may define some classes as it Listen to the class, these classes 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 Elements Each TAG element must point 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: the child element element name of the TAG element Description Name Unique element name TAG-CLASSTAG tag corresponding to the TAG processing class TEI-ClassJavax.Servlet.jsp. TAGEXT.TAGEXTRAINFO Subcombin, used to express script variables (optional) BODY-ContentTAG Tags Body Type Display-Name is visualized by visualization tool (such as jbuilder) to display the name (optional) Small-icon is visualization tool (such as JBuilder) Large Icon (Optional) Large-ICON is used by a visual tool (such as jbuilder), a large icon (optional) Description of this TAG tag, Variable provides a script variable (with TEi-Class) (Optional) AttributeTag Tag Attribute Name The following sections describe how different TAGs are implemented specifically. Simple TagTAG Treatment Class Simple TAG Processing 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 handling class is implemented as follows: public simpletag extends tagsupport {public int dostarttag () throws jspexception {TROWS JSPEXCEPTION {TRY {pageContext.get (). Print ("Hello."); } catCH ("SimpleTag:" E.GetMessage ());} return skip_body;} public int doendtag ()}} Eval_page;}} Note: If the tag tag does not have content, Defining a Body-Content element is empty, such as Empty Tag tag tag processing class for the Tag tag, you must define its properties in accordance with the JavaBeans specification, and get and SET method. As an example of Struts's Logic: Present tag, This TAG handling 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 named ID, and your tag handling class is inherited from the tagsupport class, then you don't 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 if it must be, it can be obtained by expressing expressions such as <% = ...%>, and its type (optional), if not specified 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 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 ... < Name> Parameter false TRUE TRUE TRUE ... Attribute element checks about the valid value of the TAG tag can be description from the Tag library The document is obtained, 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, TAG tags Define below TLD as follows: attr1 true TRUE This definition shows that ATTR1 is 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) o). TOLOWERCASE (). Equals ("true") || ((String) O) .tolowercase (). Equals ("false")) Return True; Elsereturn false;} Elsereturn true;}} Tagtag processing clashot with body if tag The label contains content, which is slightly different, and it is also necessary to depend on whether the TAG processing class is interacting with Body. If you want to interact with Body, we think that the TAG handling class must be able to operate Body. The Tag handling class is not interactive with the Body if the TAG handling class is not interacting with the Body, the TAG handling class should implement the TAG interface or derive from tagsupport. If the 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 and body interactions 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 is already set in Body content, but is not called before calculations. 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 handling 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 doAfterBody () throws JspTagException {BodyContent bc = getBodyContent (); // contents extracted from body String query = bc.getString () format string; // Clear bodybc.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 Elements Because the TAG may have body, you must use the body-content element to specify the type of body content: jsp | tagDepend If the content of the body is custom or internal Tag, scripting elements, or HTML, 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. Using Tags Defined Script Variable TAG Processing Class TAG Processing class is responsible for creating or setting the script variables defined in the page, implemented with pagecontext.setttribute (name, value, scope), or pagecontext.setttribute (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.

Object Licensing Period (Scope) As shown in the table: Object Survival period Table Name Accessibility Survival period Page Current page has been valid unless page is submitted or redirected to a new page request current page or the current page redirected The page has always been valid unless the page is submitted to the customer's response session current page or the page in the same browser window has always been valid unless there is all the requests for the current browser, timeout, the network fault Application entire web application has been valid, unless a network failure occurs The server fault provides information about script variables The following example defines a script variable named "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 the code about this book (synchronization can avoid several customers to access this book. Conflicts caused by generating synchronous code, the JSP engine needs to know the following information of this script variable:? Script variable name? Class belonging to the script variable? Does this script variable reference a new or existing object? 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 property name Name-Given given during compile 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 references a new object, default is TRUE. • Scope? D? D script variable range, default is NESTED. The following table describes several types of Scope: The valid range value of the script variable The valid range value of the NESTED is between the start and end of the TAG tag, if the TAG handling class implements the BodyTag interface, then call in DOINITBODY and DOAFTERBODY, otherwise call in dostartTAG At_begin starts from the Tag tag until the page ends if the TAG handling class implements the BodyTag interface, call at_endtag and DOENDTAG in DONITTTTTTAG and DOENDTAG until the end of the TAG tag until the end of the page Struts Tried an example, its Bean: DEFINE tag implementation following JSP 1.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 group class named VariableInfo, which includes the following information: • Variable name? Variable class name? Does this variable a new object? This variable is a valid range JSP engine will The parameter named DATA is passed to the GetVariableInfo method, including all "property names? D? D attribute values" in the Tag tag 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 with the Data.GetAttributeString method. 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 ("ID"), TYPE, TRUE, VARIABLEINFO.AT_BEGIN}};}} Note: About the extra tag information class class name must be in TAG tag in TLD -Class sub-elements are defined. Therefore, definition in Definetei's TEI-Class looks like this: org.apache.struts.taglib.bean.definetagtei Tagtag with collaborative relationships collaborates through sharing objects, JSP technology Support for 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 doStartTag () throws JspException {String cid = getConnection (); if (! cid = null) {// there is a connection id, the use of it. connection = (Connection) pageContext.getAttribute (cid);} else {ConnectionTag ancestorTag = (ConnectionTag) findAncestorWithClass (this, ConnectionTag.class); if (ancestorTag == null) {throw new JspTagException ( "without a connection attribute query label Must be tagged by a Connection.

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

New Post(0)