JSP Custom Labels

Source: Internet
Author: User
Tags list of attributes tld

First, the basic concept

1, tag (tag)

tags are XML elements that make JSP pages simple and easy to maintain, and can easily implement the same JSP file to support multiple language versions. Because the label is an XML element, its name and attributes are case-sensitive.

2. Tag libraries (Tag library)

A collection of functionally similar, logically interrelated tags is called a tag library.

3. Tag library description file (tag libraries descriptor)

The tag library description file is an XML file that provides a mapping of tag references in classes and JSPs in the tag library. It is a configuration file, and the Web. XML is similar.

4, Label processing class (Tag Handle Class)

The label processing class is a Java class that inherits the TagSupport or extends the Simpletag interface, which enables the specific functions of the custom JSP tag.

II. format of custom JSP tags

1, in order to enable the JSP container to use the custom behavior in the tag library, the following two conditions must be met:

<% @ taglib prefix= "Someprefix" uri= "/sometaglib"%>

1) Identify the label that represents this custom behavior from a specified tag library;
2) Find the specific class that implements these custom behaviors.

The first required condition-to find out a custom behavior belongs to that tag library-is done by the prefix (Taglib Directive ' s Prefix) attribute of the label directive, so elements that use the same prefix in the same page belong to this tag library. Each tag library defines a default prefix that is used to insert a custom label in the document in the tag library or in the page. So, you can use prefixes such as JSP,JSPX,JAVA,SERVLET,SUN,SUNW (which are all reserved words specified in the JSP white paper).

The URI attribute satisfies the second requirement above. Find the corresponding classes for each custom behavior. This URI contains a string that the container uses to locate the TLD file. The name of all label processing classes in the tag library can be found in the TLD file.

2. When the Web application starts, the container searches for all files ending with the. TLD from the Meta-inf of the directory structure of the Web-inf folder. This means that they will locate all TLD files. For each TLD file, the container first obtains the URI of the tag library and then creates a mapping relationship for each TLD file and the corresponding URI.

In the JSP page, we only need to match the specific tag library by using the Tag Library directive with the URI attribute value.

Third, the custom JSP label processing process

1. Introduction of Tag Library in JSP

<% @ taglib prefix= "Taglibprefix" uri= "Tagliburi"%>

2. Use tag library tags in jsp

3. The Web container obtains the URI attribute value of the taglib declared in the first step, based on the prefix in the second step

4. The Web container finds the corresponding element 5, based on the URI attribute, at web. Xml. Gets the value of the corresponding element from the element 6. The Web container finds the corresponding. tld file 7 from the web-inf/directory based on the value of the element. Find the element 8 that corresponds to TagName from the. tld file. Gets the value of the corresponding element in the element 9. The Web container creates an instance of the corresponding tag handle class based on the value of the element 10. The Web container invokes this instance of the Dostarttag/doendtag method to complete the corresponding processing.

Iv. basic steps for creating and using a tag library

1, create the Label processing class (Tag Handler Class)

2. Create tag library profile (tag libraries Descrptor file)

3. Configure element 4 in the Web. xml file. Attracting tag libraries in JSP files

V. Introduction to TagSupport Class

1. The class that handles the label must extend the Javax.servlet.jsp.TagSupport.

2. The main properties of the TagSupport class:

A.parent Property: Represents the processing class that nested the upper label of the current label;

B.pagecontex property: Represents a Javax.servlet.jsp.PageContext object in a Web application;

3, JSP container before calling doStartTag or Doendtag method, will call Setpagecontext and SetParent method, set PageContext and parent. Therefore, the PageContext variable can be accessed directly in the label processing class.

4. The PageContext member variable cannot be accessed in the TagSupport construction method because the JSP container has not yet called the Setpagecontext method to initialize the PageContext.

#p #

Vi. methods of TagSupport handling labels

1. The TagSupport class provides two ways to handle labels:

public int doStartTag () throws Jspexception
public int Doendtag () throws Jspexception

2, doStartTag: But the JSP container encounters the start flag of the custom label, it calls the doStartTag () method.

The doStartTag () method returns an integer value that is used to determine the subsequent process of the program.

A.tag.skip_body: Say ... The content between is ignored;

B.tag.eval_body_include: Indicates that the contents between the tags are executed normally.

3, Doendtag: But the JSP container encounters the end flag of the custom label, it calls the Doendtag () method. The Doendtag () method also returns an integer value used to determine the program's subsequent process.

A.tag.skip_page: To stop the execution of the Web page immediately, the non-processed static content on the webpage and the JSP program are ignored any existing output content is immediately returned to the customer's browser.

B.tag_eval_page: Indicates that the JSP Web page continues to execute according to the normal process.

VII. user-defined label properties

If a custom attribute is also included in the label, the attribute should be used as a member variable in the label processing class, and the method of setting and reading the property is provided separately.

Viii. steps to create a label processing class

1. Create a file that contains the static text of the JSP Web page (that is, the text to replace the custom JSP tag);
2, loading static text when the Web application starts;
3. Create a label processing class.

Ix. How to create a file containing static text for a JSP web page

1. Use the Java.util.Properties class to store static text to replace custom JSP tags in web pages;

2. The Properties class represents a collection of attributes, which can be either saved to a stream or loaded from a stream. The text is stored as key/value in the Web-inf directory, such as Key=value, which are string types in the attribute list.

X. Common APIs for the properties class

1. SetProperty (string key, String value): Call the Put method of the Hashtable class to add a property;

2. GetProperty (String key): Gets the attribute value corresponding to key in the attribute list;

3. Load (InputStream in): reads the list of attributes from the input stream object InputStream (properties lists);

4. Store (OutputStream out,string coMMent): Writes the property pairs of the property list to the output stream object using the appropriate format, by default using the ISO-88590-1 encoding format, which processes the input in a row. The Key/value of the property is paired with "=,:", with carriage return, newline delimited key/value pairing.

Xi. Common APIs for the ServletContext class

1, GetContext (String Uripath): Returns the ServletContext object represented by Uripath in the server;

2, Getinitparameter (String name): Returns the value of the name parameter in the ServletConfig object;

3, Getminetype (String file): Returns the MIME type of the file represented by the filename parameter;

4, Getrequestdispatcher (String path): Returns the Requestdispacher object represented by path;

5. getResourceAsStream (String Path): Returns the resource corresponding to path in the form of an input stream, in which the object can be any form of data, and the path parameter must start with "/" and relative to the context Root.

12. How to use Servletcontxt to read and save a property file

1, create Java.util.Properties class object;

2, obtain ServletContext object;

3. The property file is read into an input stream object in the form of an input stream;

4. Load the input stream object into the Properties object;

5. Save the Properties object to the ServletContext object.

13. How to load static text when the Web app starts

1. Create a subclass that inherits the HttpServlet class and set the Load-on-startup property when configuring this servlet in Web. xml:

SomeClass
Somepackage. SomeClass1

2. Create the Java.util.Properties class in the Init () method of this servlet

3. Get the ServletContext object for the current web App

4. Read the properties file in the Web-inf directory into the input stream InputStream:

InputStream in = context.getresourceasstring ("web-inf/someproperties.properties");

5. Load the input stream into the Property object

Ps.load (in);

6. Save the attribute object to the top

Context.setattribute ("AttributeName", PS);

#p #

14. How to create a label processing class

1. Introduction of necessary resources




Import java.io.*;

2. Inherit the TagSupport class and overwrite the doStartTag ()/doendtag () method

3. Get the Java.util.Properties object from the ServletContext object

4. Get the attribute value corresponding to the key from the Properties object

5, the corresponding processing of the acquired properties and output results

XV, create tag library profile (Tag libraries descriptor)

1, Tag library description file, referred to as TLD, using XML file format, defines the user's tag library. The elements in a TLD file can be divided into 3 categories:

A. Tag library elements
B. Label elements
C. Tag attribute Element

2, Tag library elements used to set the tag library related information, its common properties are:

A.shortname: Specifies the default prefix name (prefix) of the tag library;

B.uri: Sets the unique access identifier for the tag library.

3, the label element is used to define a label, its common properties are:

A.name: Set the name of the tag;

B.tagclass: Set the processing class of tag;

C.bodycontent: Sets the body (body) content of the label.

1) Empty: Indicates that there is no body in the label;
2) JSP: The body of the tag can be added to the JSP program code;
3) Tagdependent: Indicates that the contents of the tag are handled by the label itself.

4. The tag attribute element is used to define the property of the label, and its common properties are:

A.name: attribute name;
B.required: property is required, default is false;
C.rtexprvalue: Whether the property value can be an request-time expression, that is, an expression similar to <%=...% >.

16. Using tags in Web applications

1. If a custom JSP tag is used in the Web application, you must include the element in the XML. file, which declares the tag library where the referenced label is located

/sometaglib
/web-inf/sometld.tld

2, set the tag library unique identifier, in the Web application will be based on it to reference tag Libray;

3. Specify the location of the TLD file corresponding to the tag library;

4, in the JSP file need to join <% @ taglib% > directive to declare a reference to the tag library. For example:

<% @ taglib prefix = "Someprefix" uri = "/someuri"%>

5. prefix represents the prefix used to refer to this tag library's label in a JSP Web page, which specifies the identifier of the tag libraries, which must be consistent with the attributes in Web. Xml.

Example:

Displaytag class:
 PackageCn.xs.displaytag;Importjava.io.IOException;Importjavax.servlet.jsp.JspException;ImportJavax.servlet.jsp.JspWriter;ImportJavax.servlet.jsp.tagext.TagSupport; Public classDisplaytagextendstagsupport{Private Static Final LongSerialversionuid = 1L; @Override Public intdoStartTag ()throwsjspexception {System.out.println ("doStartTag ()"); returnEval_body_include; } @Override Public intDoafterbody ()throwsjspexception {System.out.println ("Doafterbody ()"); returnSkip_body; } @Override Public intDoendtag ()throwsjspexception {System.out.println ("Doendtag ()"); JspWriter out= This. Pagecontext.getout (); Try{out.print ("); Out.print ("Hello world!"); Out.print ("); } Catch(IOException e) {e.printstacktrace (); }            return Super. Doendtag (); }}

Display.tld

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE taglib Public "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.1//en" "http://java.sun.com/j2ee/dtds/ Web-jsptaglibrary_1_1.dtd "><taglib>    <tlibversion>1.0</tlibversion>    <jspversion >1.1</jspversion>    <shortname>bean</shortname>    <uri>/web-inf/tld/display.tld </uri>    <tag>        <name>display</name>        <tagclass> cn.xs.displaytag.displaytag</tagclass>        <bodycontent>JSP</bodycontent>        <attribute >            <name></name>            <required></required>            <rtexprvalue></ rtexprvalue>        </attribute>    </tag></taglib>

INDEX.JSP:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "    pageencoding=" iso-8859-1 "%>    <%@ taglib uri="/web-inf/tld/display.tld " prefix= "Test"%>    <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Engineering Structure:

Run:

Some of the data collected from the Internet ....

JSP Custom Labels

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.