Custom labels in a JSP page

Source: Internet
Author: User
Tags define definition empty event listener expression html form variables variable
Custom labels in js| page JSP pages



Custom labels in a JSP page
Stephanie Bodoff
Standard JSP tags used to invoke operations in the Javaean component and execute request assignments simplify the development and maintenance of JSP pages. JSP technology also provides a mechanism for encapsulating other dynamic functions in a custom label, which is an extension of the JSP language. Custom tags are usually in the form of a tag library that defines a set of related custom labels and contains objects that implement those tags.

Tasks that can be performed by custom labels include actions on implicit objects, processing forms, accessing databases, and other enterprise-class services, such as e-mail and catalogs, and executing process control. Using these tags, the JSP tag library is created by developers who are proficient in the Java programming language and familiar with accessing databases and other services, and Web application developers can focus on content rendering without having to worry about accessing enterprise-class services. Just as encouraging the separation of library developers from the work of library users, custom tags increase productivity by encapsulating repetitive tasks that enable them to be reused in multiple applications.

JSP technology community to give tag library very high attention. For information about the tag library and the address of some free libraries, see

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

What is a custom label?
Custom labels are user-defined JSP language elements. When the JSP page that contains the custom label is converted to a servlet, the label is converted to an operation on an object named tag handler. These operations are then invoked by the Web container when the servlet of the JSP page executes.

Custom tags are rich in functionality. They can

· Custom-made by attributes passed from the calling page.

· Access all the objects that the JSP page can use.

· Modifies the response generated by the calling page.

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

· Nested within each other, you can implement complex interactive interactions in your JSP pages.

JSP Page Example
This chapter describes the tasks involved in using and defining labels. This chapter demonstrates these tasks with a rewritten version of the Duke's Bookstore application, which is discussed in the JSP page example, that takes advantage of the advantages of the two tag libraries: struts and tutorial-template. The third section of this chapter provides a detailed description of two tags: a set of labels in the iterate and tutorial-template tag libraries in STRUTST.

The Struts Tag Library provides a framework for building an internationalized Web application that implements the model-view-control design pattern. Struts includes a complete set of custom tool tags for handling:

· HTML form

· Template

· JavaBeans components

· Logical processing

The Duke's bookstore application uses a label from the struts Bean and the logic sub Library.

The Tutorial-template tag library defines a set of labels that are used to create application templates. Templates are JSP pages with placeholders that need to be changed in each screen. Each placeholder is called a parameter of the template. For example, a simple template might include the title argument at the top of the generated screen, and the body parameter of a JSP page as the custom content of the screen. Templates are--definition, screens, and parameter--that are created with a set of embedded tags that they use to build the Duke's Bookstore screen definition table and insert the parameters from the table into the screen with the Insert label.

Figure 16-1 shows the request flow through the Duke ' s bookstore Web Component:

· Template.jsp, template.jsp determines the structure of each screen. It uses the Insert tab to make up the screen with subassemblies.

· Screendefinitions.jsp, which defines the subcomponents that each screen uses. All screens have the same banner, but the title and body are different (specified by the JSP page column in table 15-1).

· Dispatcher, this is a servlet that processes the request and transfers it to template.jsp.



Figure 16-1 Request flow through the Duke ' s bookstore component

The source code for the Duke's bookstore application is located in the Docs/tutorial/examples/web/bookstore3 directory that is generated when the tutorial package (see run example) is extracted. To compile, deploy, and run this example, you need to:

1. Download the struts version 1.0.2 from the following address

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 the <jwsdp_home>/docs/tutorial/examples/bookstore3.

4. Run the ant build. The build target makes all necessary compilations and copies the files to the <jwsdp_home>/docs/tutorial/examples/web/bookstore3/build target.

5. Ensure that Tomcat has been started.

6. Run ant install. The install target notifies Tomcat that there is already content.

7. If you have not done so, start the Pointbas database server and add data (see Accessing the database from the Web application).

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

Help on troubleshooting common problems see frequently asked questions and their solutions and troubleshooting.

Using labels
This section describes how JSP pages use labels and describes different types of labels.

To use labels, the page creator must do the following two things:

· Declare a tag library containing labels

· Make the tag library implementation available for Web applications

Declaring tag libraries
By adding the TAGLIB directive to the page before using any custom labels, declaring the JSP page will use the label defined in the tag library:

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

The URI attribute represents a URI that uniquely identifies the tag library descriptor (TLD), and the URI is described in the tag Library descriptor. This URI can be either direct or indirect. The prefix property defines a prefix that distinguishes the labels defined by the specified tag library from the labels provided by other tag libraries.

The tag library descriptor file name must have an extension. tld. TLD files are stored in the Web-inf directory of the War, or in Web-inf subdirectories. TLD can be referenced directly or indirectly.

The following Taglib directive refers directly to a TLD file name:

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

This taglib instruction uses a short logical name to refer to the TLD indirectly:

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

Maps the logical name to an absolute location in the Web application deployment descriptor. To map the logical name/tutorial-template to absolute position/web-inf/tutorial-template.tld, add element taglib to Web.xml:

<taglib>
<taglib-uri>/tutorial-template</taglib-uri>
<taglib-location>
/web-inf/tutorial-template.tld
</taglib-location>
</taglib>

Make the tag library implementation available
You can make the tag library implementation available to Web applications in two ways. A class that implements a label handler can be stored in a web-inf/classes subdirectory of a Web application in a non packaged form. Alternatively, if you publish the library as a jar, store it in the Web-inf/lib directory of your Web application. Tag libraries that are shared in multiple applications are stored in the Java WSDP <jwsdp_home>/common/lib directory.

Label type
JSP custom tags are written in XML syntax. They have a start and end tag, and possibly a text:

<tt:tag>
Body
</tt:tag>

A custom label with no body text is represented as follows:

<tt:tag/>

Simple label
A simple label has no body and no attributes:

<tt:simple/>

Tagged with attributes
Custom labels can have attributes. The property is listed in the start tag, and the syntax is attr= "value". As with the behavior of custom methods, attribute values are used to customize the behavior of custom labels. Specify the type of label attribute in the tag library descriptor (see tagged with attribute).

You can set property values with a constant or run-time expression. The conversion process between constants and Run-time expressions and property types follows the JavaBean component property rules that are described in setting JavaBean component properties.

The properties of the Struts logic:present label determine whether the body of the label is judged. In the following example, a property specifies that a parameter clear named is required:

<logic:present parameter= "Clear" >

Duke's Bookstore Application page catalog.jsp uses the Run-time expression to set the value of the property, which determines which books the Struts logic:iterate tag will enumerate.

<logic:iterate collection= "<%=bookdb.getbooks ()%>"
Id= "book" Type= "database. BookDetails ">

Tagged with body
A custom label can contain custom and core tags, script elements, HTML text, and a label-dependent body content between the start and end tags.

In the following example, the Duke ' s bookstore Application page showcart.jsp use the Struts logic:present tag to clear the cart and print a message if the request contains a parameter named clean.

<logic:present parameter= "Clear" >
<% cart.clear (); %>
<font color= "#ff0000" size= "+2" ><strong>
You just cleared your shopping cart!
</strong><br> <br></font>
</logic:present>

Choose to pass information with attributes or body text
As shown in the last two sections, you can pass the given data as the property of the label or the body of the label. In general, any simple string or data generated by a simple expression can best be passed as a property.

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

<tt:lookupegin (); %> id= "TX" type= "UserTransaction"
Name= "Java:comp/usertransaction"/>
<% tx.b

In the Duke's Bookstore application, several pages use Struts's bean-oriented tabs to define script variables. For example, BOOKDETAILS.JSP uses the bean:parameter tag to create a script variable BookID and set it up and set it to the value of the request parameter BookID. The Jsp:setproperty statement also sets the BookID property of the Bookdb object to the value of the request parameter BookID. The bean:define tag extracts the value of the BookDetails property bookdetails of the bookstore database and defines the result as a 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 "/>

Action Label
Custom tags can work with each other through shared objects.

In the following example, Tag1 creates an object named Obj1, which is returned by Tag2.

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

In the following example, an object created by the perimeter label in a set of nested labels is available for all internal tags. Because the object is not named, a potential naming conflict can be reduced. This example shows what a group of collaborative embedded tags will look like in a JSP page.

<tt:outerTag>
<tt:innertag/>
</tt:outerTag>

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

Define Labels
To define a label, you need to:

· Develop a tag handler and helper class for the tag

· Declare this label in the tag library descriptor

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

Label Handler
The label handler is an object called by the Web container that is used to judge a JSP page with a custom label. Tag handler must implement the tag or Bodytag interface. An interface can be used to accept an existing Java object and make it a label 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 servlet of the JSP page invokes the label handler defined by the tag and Bodytag interface at different stages of the label processing. When the start tag of a custom label is encountered, the servlet of the JSP page invokes the method to initialize the corresponding handler, and then invokes the handler doStartTag method. Invokes the Doendtag method of the processor when the end tag of a custom label is encountered. Call other methods when the label handler needs to interact with the body of the label, see the label with the body. To provide the implementation of the label handler, you must implement the methods that are invoked at different stages of processing the label and summarize these methods in table 16-1.

Table 16-1 Label Handler method

Label handler type
Method

Simple
doStartTag, Doendtag, release

Property
doStartTag, Doendtag, set/getattribute1 ... N, Release

Body, judgment and no interaction
doStartTag, Doendtag, release

Text, iterative judgment
doStartTag, Doafterbody, Doendtag, release

Body, interaction
doStartTag, Doendtag, release, Doinitbody, Doafterbody, release


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), through which the tag handler can obtain all other implicit objects (requests, sessions, and applications) that the JSP page can access.

An implicit object can have a named property associated with it. This property can be accessed using the [Set|get]attribute method].

If the label is embedded, the label handler can also access the handler called parent, which is associated with the perimeter label.

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

Tag Library Descriptor
A tag library descriptor (TLD) is an XML document that describes a tag library. The TLD contains information about the entire library and each label contained in the library. Web containers use TLD to validate 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 Web-inf directory of the war file or in Web-inf subdirectories.

The TLD must start with the preamble (prolog) of the XML document that specifies the version and document type definition (DTD) of the XML.

<?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 ">
Tomcat supports versions 1.1 and 1.2 of DTDs. However, the 1.2 version is discussed in this chapter because the latest version should be used in all the tag libraries that are being developed. Template Library Tldtutorial-template.tld conforms to version 1.2. The Struts library TLD conforms to the version 1.1 DTD, which has fewer elements, and some of these elements use slightly different names.

The root of the TLD is the taglib element. The child elements of Taglib are listed in table 16-2:

Table 16-2 taglib child elements

Elements
Description

Tlib-version
version of the tag library

Jsp-version
The JSP specification version required by this tag library

Short-name
JSP page Authoring tool can be used to create an optional name for a help-bearer

Uri
URI that uniquely identifies the tag library

Display-name
The optional name that will be displayed by the tool

Small-icon
Optional small icon to be used by the tool

Large-icon
Optional large icon to be used by the tool

Description
Optional label-specific information

Listener
See Listener elements

Tag
See tag element



Listener element
The tag library can specify some event listener classes (see Handling Servlet lifecycle events). These listeners are listed as listener elements in the TLD, and the Web container initializes the listener classes and registers them in a manner similar to the listener defined at the war level. Unlike the war class listener, the order in which the tag library listener registers is not specified. The unique child element of the listener element is the Listener-class element, and it must contain the fully qualified name of the Listener class.

Tag element
Each label in the library is described by a class that gives its name and its label handler, information on the script variable created by the label, and information on the Label property. The script variable information can be given directly in the TLD, or it can be given by the tag extra info class (see the label that defines the script variable). Each property declaration contains the content that indicates whether the property is required, whether its value can be determined by the request-time expression, and the property type (see property Element).

Specifies the label in the TLD in the tag element. The child elements of tag are shown in table 16-3:

Table 16-3 Tag child elements

Elements
Description

Name
Unique label Signature

Tag-class
Label handler fully qualified name of class

Tei-class
An optional subclass of the Javax.servlet.jsp.tagext.TagExtraInfo. See providing information about script variables.

Body-content
Body content type. See Body-conten elements and body-content elements.

Display-name
Optional name 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 label-specific information

Variable
Optional script variable information. See providing information about script variables.

Attribute
Label Property information. See attribute element.


The following sections describe the methods and TLD required to develop each type of label that is described in the label type.

Simple label
Label Handler
The handler of a simple label must implement the doStartTag and Doendtag methods of the tag interface. Invokes the doStartTag method when the start tag is encountered. Because the simple label has no body, this method returns Skip_body. Invokes the Doendtag method when an end tag is encountered. If you want to judge other parts of the page, the Doendtag method needs to return eval_page, otherwise it returns Skip_page.

The simple label discussed in the first section

<tt:simple/>

Implemented by the following label 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 that do not have body text must declare that their body content is empty by using the body-content element:

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


Custom labels in a JSP page



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.