Custom tag in JSP page

Source: Internet
Author: User
Tags tld
The standard JSP tag used to call operations in the javaean component and execute Request dispatch simplifies the development and maintenance of JSP pages. JSP technology also provides Custom tagEncapsulation of other dynamic functions. This custom tag is an extension of the JSP language. Custom tags are usually Tag LibraryIt defines a set of related custom tags and contains objects that implement these tags.

Tasks that can be executed with custom tags include operations on Implicit objects, form processing, database access, and other enterprise-level services, such as email and directory, and execution process control. JSP tag libraries are created by developers who are proficient in the Java programming language and are very familiar with accessing databases and other services, web application developers can focus on content presentation without worrying about how to access enterprise-level services. Just as we encourage library developers to separate their work from library users, custom tags encapsulate repeated tasks so that they can be reused in multiple applications, this increases productivity.

The JSP technology community attaches great importance to the tag library. For information about the tag Library and the addresses of some free libraries, see

Http://java.sun.com/products/jsp/taglibraries.html

What is a custom tag?

Custom tags are custom JSP language elements. When a JSP page containing a custom tag is converted to a servlet, the tag is converted toTag Handler. Then, when the servlet of the JSP page is executed, the Web Container will call these operations.

Custom tags have rich functions. They can

· You can customize the attributes passed from the call page.

· All objects that can be used to access the JSP page.

· Modify the response generated by the call page.

· Communicate with each other. You can create and initialize the JavaBean Component, create a variable that references the bean in one tag, and then use the bean in another tag.

· Nested with each other. You can implement complex interaction on JSP pages.

JSP Page example

This chapter describes the tasks involved in using and defining tags. This chapter uses the modified section of the JSP version Duke's bookstore application discussed in the JSP page example to demonstrate these tasks. The rewriting utilizes the advantages of the two tag libraries: struts and tutorial-template. Section 3 of this ChapterExampleTwo tags are described in detail: iterate in strutst and a group of tags in the tutorial-template tag library.

StrutsThe tag Library provides a framework for building an international web application that implements Model-View-control design mode. Struts includes a complete set of custom tool labels for processing:

· HTML form

· Template

· JavaBeans Components

· Logic processing

The Duke's bookstore application uses the labels in the struts bean and logic sub-libraries.

The tutorial-template tag library defines a set of tags used to create an application template. A template is a JSP page with placeholders that need to be changed on each screen. Each placeholder is called a template parameter. For example, a simple template may include the title parameter at the top of the generated screen, and a JSP page as the body parameter of the customized screen content. A template is created with a set of embedded tags -- Definition, screen, and parameter -- they are used to build Duke's bookstore screen definition tables, and insert parameters from the table into the screen using the insert tag.

Figure 16-1 shows the request process through the Duke's bookstore Web component:

· Template. jsp and template. jsp determine the structure of each screen. It uses the insert label and child components to form the screen.

· Screendefinitions. jsp, which defines the child components used on each screen. All screens have the same banners, but the title and body are different (specified by the JSP page column in table 15-1 ).

· DISPATCHER: This is a servlet that processes requests and forwards them to template. jsp.

Figure 16-1 request process through the Duke's bookstore component

The source code of the Duke's bookstore application is located in the extract tutorial package (seeRunning exampleIn the generated docs/tutorial/examples/web/bookstore3 directory. To compile, deploy, and run this example, You need:

1. Download struts version 1.0.2 from the address below

Http://jakarta.apache.org/builds/jakarta-struts/Release/v1.0.2/

2. Extract struts and copy struts-bean.tld, struts-logic.tld, and Struts. jar from jakarta-struts-1.0/lib to <Jwsdp_home>/Docs/tutorial/examples/web/bookstore3.

3. In the terminal window, enter <Jwsdp_home>/Docs/tutorial/examples/bookstore3.

4. Run ant build. The build target will perform all necessary compilation and copy the file to <Jwsdp_home>/Docs/tutorial/examples/web/bookstore3/build target.

5. Make sure that tomcat has been started.

6. Run ant install. The Install target notifies Tomcat that the content already exists.

7. If not, start the pointbas database server and add data (seeSlaveAccess the database in a web application ).

8. Open the bookstore URL http: // localhost: 8080/bookstore3/Enter.

For more information about how to diagnose common problems, seeFAQs and SolutionsAndTroubleshooting.

Use tags

This section describes how to use tags on the JSP page and describes different types of tags.

To use tags, page writers must do the following:

· Declare the tag library containing tags

· Make the tag library available for Web Applications

Declare a tag Library

Before using any custom tag, add the taglib command to the page to declare that the JSP page will use the tag defined in the tag Library:

<% @ Taglib uri = "/WEB-INF/tutorial-template.tld" prefix = "TT" %>

The URI attribute indicates the URI that uniquely identifies the tag library Descriptor (TLD). The URI is described in the tag library descriptor. This URI can be direct or non-direct. The prefix attribute defines the prefix between the tag defined by the specified tag Library and the tag provided by other tag libraries.

The name of the tag library descriptor must have the extension. TLD. TLD files are stored in the war's WEB-INF directory, or in the subdirectory of the WEB-INF. TLD can be referenced directly or indirectly.

The following taglib command directly references a TLD File Name:

<% @ Taglib uri = "/WEB-INF/tutorial-template.tld" prefix = "TT" %>

This taglib command indirectly references TLD using a short logical Name:

<% @ Taglib uri = "/tutorial-template" prefix = "TT" %>

Map logical names to an absolute location in the Web application deployment descriptor. To map logical name/tutorial-template to absolute location/WEB-INF/tutorial-template.tld, add the element taglib in Web. xml:

<Taglib>
<Taglib-Uri>/tutorial-template </taglib-Uri>
<Taglib-location>
/WEB-INF/tutorial-template.tld
</Taglib-location>
</Taglib>

Make the tag library available

The tag library can be available to Web applications in two ways. The label handler class can be stored in the WEB-INF/classes subdirectory of the Web application in a non-packaged form. Another way is to release the library as a jar, store it in the WEB-INF/lib directory of the Web application. The tag library shared among multiple applications is stored in the Java wsdp <Jwsdp_home>/Common/lib directory.

Tag type

JSP custom tags are written in XML syntax. They have a start tag and end tag, and may have the body:

<TT: Tag>
Body
</TT: Tag>

Custom tags without body are as follows:

<TT: tag/>

Simple tag

A simple tag has no body or attributes:

<TT: simple/>

Tags with attributes

Custom tags can contain attributes. Attribute columns are in the start tag. The syntax is ATTR = "value ". The property value is used to customize the behavior of tags, just like the behavior using parameter customization methods. Specify the tag attribute type in the tag library Descriptor (see tags with attributes ).

You can use a constant or runtime expression to set the attribute value. The conversion process between constants and runtime expressions and attribute types follows the JavaBean Component Attribute rules described in setting JavaBean Component attributes.

Struts logic: the attribute of the present tag determines whether to judge the label body. In the following example, a property requires the clear parameter:

<Logic: Present parameter = "clear">

On the Duke's bookstore application page, catalog. jsp uses a runtime expression to set the attribute value. It determines which books the struts logic: iterate tag should enumerate.

<Logic: iterate collection = "<% = bookdb. getbooks () %>"
Id = "book" type = "database. bookdetails">

Label with body

Custom tags can contain custom and core tags, script elements, HTML text, text between the start and end tags, and text content dependent on tags.

In the following example, the Duke's bookstore application page showcart. jsp uses the struts logic: Present tag to clear the shopping cart, and prints a message if the request contains a parameter named clear.

<Logic: Present parameter = "clear">
<% Cart. Clear (); %>
<Font color = "# ff0000" size = "+ 2"> <strong>
You just cleared your shopping cart!
</Strong> <br> & nbsp; <br> </font>
</Logic: Present>

Choose to pass information with attributes or body

As shown in the last two sections, you can pass the given data as the attribute of the tag or the body of the tag. Generally, any simple string or data generated by judgment on a simple expression is best transmitted as an attribute.

Tag defining script variables

Custom tags can define variables that can be used in scripts on the page. The following example shows how to define and use a script variable that contains an object returned from the JNDI query. Examples of such objects include enterprise beans, transactions, databases, and environment items:

<TT: lookupegin (); %> id = "TX" type = "usertransaction"
Name = "Java: COMP/usertransaction"/>
<% Tx. B

In the Duke's bookstore application, several pages use Struts-oriented bean labels to define script variables. For example, bookdetails. jsp uses the bean: parameter label to create the script variable bookid, set it, and set it as the value of the Request Parameter bookid. The JSP: setproperty statement also sets the bookid attribute of the bookdb object to the value of the Request Parameter bookid. BEAN: Define label extracts the value of bookdetails in the bookdetails attribute of the bookstore database and defines the result as the script variable book:

<Bean: parameter id = "bookid" name = "bookid"/>
<JSP: setproperty name = "bookdb" property = "bookid"/>
<Bean: Define id = "book" name = "bookdb" property = "bookdetails"
Type = "database. bookdetails"/>
<H2> <JSP: getproperty name = "book" property = "title"> </H2>

Operation tag

Custom tags can work with each other through shared objects.

In the following example, tag1 creates an object named obj1, and then tag2 returns this object.

<TT: tag1 attr1 = "obj1" value1 = "value"/>
<TT: tag2 attr1 = "obj1"/>

In the following example, objects created from peripheral labels in a group of nested labels are available for all internal labels. Because the object is not named, potential naming conflicts can be reduced. This example shows what a group of collaborative embedded tags will look like on the JSP page.

<TT: outertag>
<TT: innertag/>
</TT: outertag>

The Duke's bookstore page template. jsp uses a set of collaboration tags to define the screen of the application. These tags are described in the template tag library.

Define tags

To define a tag, you must:

· Develop a tag handler and helper class for this tag

· Declare this tag in the tag library Descriptor

This section describes the attributes of tag handler and TLD, and explains how to develop tag handler and library descriptor elements for the tags described in the previous sections.

Tag Handler

TagHandlerIs an object called by a Web container. It is used to judge the tag when executing a JSP page with a custom tag. The tag handler must implement the tag or bodytag interface. The interface can be used to accept an existing Java object and make it a tag handler. For newly created processors, you can use the tagsupport and bodytagsupport classes as the base classes. These classes and interfaces are included in the javax. servlet. jsp. tagext package.

The JSP page servlet calls the tag handler defined by the tag and bodytag interfaces at different stages of tag processing. When the start label of the custom tag is encountered, the servlet of the JSP page calls the method to initialize the corresponding handler, and then calls the dostarttag method of the handler. The doendtag method of the processor is called when the end tag of the custom tag is encountered. Call other methods when the label handler needs to interact with the label's body. For details, see the label with the body. To provide the Implementation of the tag handler, you must call the methods at different stages of tag processing. These methods are summarized in table 16-1.

Table16-1TagHandlerMethod

TagHandlerType

Method

Simple

Dostarttag, doendtag, release

Attribute

Dostarttag, doendtag, set/getattribute1. .. n, release

Body, judgment, and no interaction

Dostarttag, doendtag, release

Text and iterative judgment

Dostarttag, doafterbody, doendtag, release

Body and Interaction

Dostarttag, doendtag, release, doinitbody, doafterbody, release

The tag handler can use an API that allows it to communicate with JSP pages. The entry point to the API is the page context object (javax. servlet. JSP. pagecontext). The Handler tag can be used to obtain all other implicit objects (requests, sessions, and applications) that can be accessed on the JSP page ).

An implicit object can have its associated naming attributes. You can use the [set | get] attribute method to access this attribute.

If the tag is embedded, the tag handler can also access the handler associated with the peripheral tag calledParent).

A set of related tag handler classes (TAG libraries) are generally packaged and deployed as jar files.

Tag library Descriptor

Tag library Descriptor(TLD) is an XML document describing the tag library. TLD contains information about the entire library and every tag contained in the library. Web containers use TLD to verify tags, and JSP page development tools also use TLD.

The TLD file name must have an extension. TLD. TLD files are also stored in the war file's WEB-INF directory or in the subdirectory of the WEB-INF.

The TLD must start with the XML document Preface (Prolog) of the specified XML version and document type definition (DTD.

<? XML version = "1.0" encoding = "ISO-8859-1"?> <! Doctype taglib public "-// Sun Microsystems, Inc. // dtd jsp tag library 1.2 //" http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd ">

Tomcat supports DTD versions 1.1 and 1.2. However, this chapter discusses version 1.2, because the latest version should be used in all developed tag libraries. The template library TLDtutorial-template.tld conforms to version 1.2. The struts library TLD conforms to the DTD of Version 1.1. It has fewer elements and some of them use slightly different names.

The root of TLD is the taglib element. Table 16-2 lists the child elements of taglib:

Table16-2 taglibChild Element

Element

Description

Tlib-version

Version of the tag Library

JSP-version

JSP standard version required by this tag Library

Short-name

The JSP page writing tool can be used to create an optional name for the nickname

Uri

URI that uniquely identifies the tag Library

Display-name

Optional names displayed by the tool

Small-icon

Optional small icons used by the tool

Large-icon

Optional large icons that can be used by tools

Description

Optional tag-specific information

Listener

See listener Element

Tag

See Tag Element

Listener Element

The tag library can specify some event listener classes (see processing servlet lifecycle events ). These listeners are listed in the TLD as listener elements. Web containers initialize listener classes and register them in a way similar to those defined at the war level. Unlike the war-level listener, the register sequence of the tag library listener is not specified here. The only sub-element of the listener element is the listener-class element, which must contain the fully qualified name of the listener class.

Tag Element

Each tag in the library is the class that gives its name and its tag handler, the information on the script variable created by the tag, and the Information Description on the tag attribute. The script variable information can be provided directly in the TLD, or through the tag extra info class (see the tag defining the script variable ). Each attribute Declaration contains the content that specifies whether the attribute is required, whether its value can be determined by the request expression, and the attribute type (see attribute element ).

Specify a tag in the TLD of the Tag Element. The sub-element of the tag is displayed in table 16-3:

Table16-3Tag child element

Element

Description

Name

Unique Tag Name

Tag-class

Fully Qualified name of the tag handler class

Tei-class

Optional subclass of javax. servlet. jsp. tagext. tagextrainfo. See provide information about script variables.

Body-content

Body content type. See the Body-conten element and body-content element.

Display-name

Optional names displayed by the tool

Small-icon

Small icons that can be used by tools

Large-icon

Large icons that can be used by tools

Description

Optional tag-specific information

Variable

Optional script variable information. See provide information about script variables.

Attribute

Tag attributes. See attribute element.

The following sections describe the methods and TLD required for each type of tag described in the tag type development.

Simple tag Handler

The handler of a simple single tag must implement the dostarttag and doendtag methods of the tag interface. Call the dostarttag method when a start tag is encountered. Because the simple label does not have the body, this method returns skip_body. Call the doendtag method when an end tag is encountered. If you want to determine other parts of the page, the doendtag method must return eval_page. Otherwise, it returns skip_page.

Simple labels discussed in Section 1

<TT: simple/>

Implemented by the following tag handler:

Public simpletag extends tagsupport {
Public int dostarttag () throws jspexception {
Try {pagecontext. getout (). Print ("hello .");
} Catch (exception ex ){
Throw new jsptagexception ("simpletag:" +
Ex. getmessage ());}
Return skip_body ;}
Public int doendtag (){
Return eval_page;
}
}

Body-content Element

Labels without the body must use the body-content element to declare that their body content is empty:

<Body-content> Empty </body-content>

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.