JSP Series 8: jstl-JSP standard tag Library

Source: Internet
Author: User
Tags control label http redirect time zone names variable scope xml attribute xsl xslt tld

I. jstl, JSP standard tag Library

* A set of standard labels used to compile and develop JSP pages. The purpose is to simplify the JSP page design.
* Composition:
Core core tag Library: http://java.sun.com/jsp/jstl/core prefix C
I18n internationalization and formatting label Library: http://java.sun.com/jsp/jstl/fmt prefix FMT
SQL label Library: http://java.sun.com/jsp/jstl/ SQL prefix SQL
XML tag Library: http://java.sun.com/jsp/jstl/xml prefix x
Funcions: http://java.sun.com/jsp/jstl/Funcions prefix FN
* Two Versions
El version and request expression version

2. Configure jstl

* Download the jsel installation package and decompress it. There are two jar packages, jstl. jar and standart. jar;
Jstl. jar contains the interfaces and related classes defined in the jstl specification;
Standart. jar contains the implementation of jstl by the Jakarta team and the TLD file of the five tag libraries in jstl;
In the WEB-INF/lib directory.
 
* Import the URL of the tag library to be used on the JSP page. The same as using custom tags.

* You can use the <tablib-URL> element in Web. XML to modify the URL reference of the tag library.

 
 
3. Core: The range variable used to operate the JSP page;
1, composition:
Common tags: Set, delete, and display the variable values created on the JSP page.
Condition Tag:
Iteration tag

* A dynamic value indicates that the attribute value can be a JSP expression or El expression, or a value set through the <JSP: attribute> label.
El provides a simplified language for accessing and operating data in JSP applications and enabling the data to be used as dynamic attribute values by jstl custom tags.

2. Common labels:

<C: Set>: set the value of the range variable or bean attribute;
* Set the range variable to VaR, value, and scope;
Set the bean property to use value, target (bean object), property (attribute name)

* The VaR and scope attributes cannot accept dynamic values. The same applies to other labels.

* Set <body-content> to JSP in TLD;

<C: Remove>: Remove a range variable;
* Scope is not specified to be removed by pagecontext. removeattribute (name.
Specify the scope to be removed by pagecontext. removeattribute (name, scope.

<C: Out>: output the expression result to the current jspwriter object;
* Similar to JSP expressions or El $ {expressions };
* Set <body-content> to JSP in TLD;
3. Condition Tag:

<C: If>: Implementation of if
* VaR is a variable of the boolean type that stores the condition results.
* Set <body-content> to JSP in TLD;
* If scope is specified, the VaR attribute must be specified. Scope default page.
* The execution result is output to the current jspwriter object.

<C: Choose>: If/else implementation,
* Determines whether the value of the test condition of the <C: When> label is true. If no condition is met, <C: ohterwise> is executed.
* Set <body-content> to JSP in TLD;
* <C: Choose> is the parent tag of <C: When> and <C: ohterwise>. <C: Choose> can only contain these two tags.

<C: When>: an optional condition;
* Set <body-content> to JSP in TLD;
* It must appear before <C: ohterwise> is used under the <C: Choose> label.

<C: ohterwise>: the final choice;

<C: Catch>: Allows initial Exception Handling on the JSP page, enabling custom error handling within the page.

4. Iteration tag
<C: foreach>: Mainly used to access and display datasets. It is usually displayed in the form of a list or a series of rows in a table.

* Iteration over the Integer Range (similar to the for statement in Java)
<C: foreach Var = "name" varstatus = "name" begin = "expression" End = "expression" step = "expression">
Body content
</C: foreach>
The begin and end attributes are either static integer values or an integer expression. They specify the initial value of the iterative index and the end value of the iterative index respectively.
When step appears, it must also be an integer. It specifies the index increment after each iteration. If the step attribute is omitted, the default step size is 1.
If the VaR attribute is specified, a variable with the specified name and limited scope will be created, and the current index value of each iteration will be assigned to the variable. You can only access it in the <C: foreach> label body.

* Iteration on the set
<C: foreach Var = "name" items = "expression" varstatus = "name" begin = "expression" End = "expression" step = "expression">
Body content
</C: foreach>

The items attribute is the only required attribute. The value of the items attribute should be a set that iterates the members of the set. Generally, the El expression is used to specify the value.
If items is specified through the item attribute marked by <C: foreach>, the named variable will be bound to subsequent elements of the set for each iteration.

<C: foreach> set supported by the marked items attribute
Item value generated by the items Value
Elements obtained by calling iterator () in Java. util. Collection
Java. util. Map java. util. Map. Entry instance
Java. util. iterator Element
Java. util. Enumeration enumeration Element
Array elements of object instances
Elements of the packaged array of basic type values
String substring that is bounded by commas (,)
Javax. servlet. jsp. jstl. SQL. Result The row obtained by the SQL query.

* Whether it is an integer or an iteration of a set, <C: foreach> the remaining attribute varstatus plays the same role.
Like the VaR attribute, varstatus is used to create a variable with a limited scope.
However, the variables named by the varstatus attribute do not store the current index value or the current element,
Instead, the javax. servlet. jsp. jstl. Core. looptagstatus class is assigned to the instance.
This class defines a set of features that describe the current iteration status,

Features of the looptagstatus object

Getter description
Current getcurrent () items of the current iteration (in the Set)
Index getindex () the index of the current iteration that starts from 0
Count getcount () number of iterations starting from 1 in the current iteration
First isfirst () indicates whether the current iteration is the first iteration.
Last islast () indicates whether the current iteration is the mark of the last iteration.
Begin getbegin () Begin Attribute Value
End getend () end Attribute Value
Step getstep () Step property value

* String iteration: the iteration is performed at intervals based on specific separator characters.

<C: fortokens>: the iteration string contains delimiter-separated members.

* Use Java. util. stringtokenizer class instances to separate strings. The delims and items attributes are their construction parameters.

* A set of delims attributes are provided to generate tags. Other attributes are the same.

* If the tag is empty or empty, no output is made.

5. url-related labels:
<C: Import>: imports a URL-based resource.
* Not only can resources under the same web application be imported, but also resources in different Web applications or websites can be imported.
* Set <body-content> to JSP in TLD;

<C: URL>: use the correct URL rewriting rule to construct a URL.

* Append the name of the current servlet context.
* Encode the URL of the Request Parameter Name and value with <C: param>
* Rewrite the URL for session management.

* The value attribute is used to specify the basic URL and mark the conversion as necessary.
If this basic URL starts with a slash, the servlet context name will be added before it. You can use the context attribute to provide an explicit context name.
If this attribute is omitted, the name of the current servlet context is used.
This is especially useful because the servlet context name is determined during deployment rather than during development.
(If this basic URL does not start with a slash, it is considered as a relative URL, and the context name does not need to be added .)

* If a value is provided for the VaR attribute (and a corresponding value can be provided for the scope attribute at the same time, this is optional ),
Assign the generated URL to the specified variable with a limited scope.
Otherwise, the generated URL is output using the current jspwriter. This ability to directly output results allows <C: URL> to mark as a value,

*

<C: Redirect>: relocate to another resource.

* Used to send an HTTP redirect response to a user's browser

* Requests are forwarded by the request dispatcher on the server, but redirection is performed by the browser.
From the perspective of developers, the forwarding proportion is more efficient.

<C: Import>: import the output result to the JSP page.
* The <C: Import> operation of the core database is more common and powerful. <JSP: Include>

* Like <JSP: Include>, <C: Import> is also a request-time operation. Its basic task is to insert the content of some other web resources into the JSP page.

* The URL attribute specifies the URL of the content to be imported. This attribute is the only required attribute of <C: Import>.
If the URL attribute value starts with a slash, it is interpreted as the absolute URL in the JSP Container at the cost.

* If no value is specified for the context attribute, such an absolute URL is considered to reference resources in the current servlet context.

* You can also specify the complete URI containing the protocol and host name as the URL attribute value. You can use any protocol supported by the java.net. url class.

* The VaR attribute stores the content obtained from the specified URL (as a string value) in a variable with a limited scope, rather than in the current JSP page.
 

Iv. Internationalization and formatting of tag Libraries

1. the HTTP protocol uses the accept-language request header to transfer localized information from the browser to the server. Many Web browsers allow users to customize their language preferences,
Browsers that do not provide explicit settings for one or more preferred language Environments will ask the operating system to determine which value (or value) is sent in the Accept-Language header ).
The servlet specification uses the getlocale () and getlocales () Methods of the javax. servlet. servletrequest class to automatically use the HTTP function.
Custom tags in the jstl FMT library use these methods to automatically determine the user's language environment and adjust their output accordingly.
However, there is no standard HTTP request header that transfers the user's time zone from the browser to the server.
 
2, composition:
Localized context Tag: sets the localized context. Other tags are operated on.
Date Tag: The tag supports formatting and parsing the date and number respectively.
Message Tag: focuses on the localization of text messages.

3. localized context tag
<FMT: setlocale>: covers the user's language environment. After the JSP Container processes the JSP code segment, the language preferences specified in the user's browser settings are ignored.
 
* Value attribute. The value of this attribute should be a string named in the language environment or an instance of the Java. util. locale class.
The language environment name is composed of two lower-case ISO language codes, which can be followed by underscores or hyphens, and two upper-case ISO country or region codes.

* The optional attribute scope is used to specify the scope of the language environment.
Page scope indicates that this setting only applies to the current page.
The request scope applies it to all JSP pages accessed during the request.
Session, the specified language environment is used for all JSP pages accessed during the user session.
Application indicates that the language environment applies to all requests of all JSP pages of the web application and all requests of all users of the application.

* The variant attribute (also optional) allows you to further customize the language environment for a specific web browser platform or vendor. For example, Mac and win

<FMT: settimezone>: Set the default time zone value used by other FMT custom tags.
* The value attribute is required, but in this example it should be an instance of the time zone name or Java. util. timezone class.
* You can call the getavailableids () Static Method of the Java. util. timezone class to retrieve a list of valid time zone names.
* Use the optional scope attribute to indicate the scope of the time zone settings.

* You can use the VaR attribute to store the value of the timezone instance in a variable with a limited scope.

<FMT: timezone>: use this tag to specify the time zone used by other jstl tags. However, the scope of the <FMT: timezone> operation is limited to the content of the TAG body.

4. date mark
<FMT: formatdate>: used to format and display the date and time (data output)

* The value attribute is required. The value should be an instance of the Java. util. Date class, specifying the date and/or time data to be formatted and displayed.
* The optional timezone attribute specifies the date and/or time of the time zone to be displayed.
* The type attribute indicates which fields of the specified date instance should be displayed, such as time, date, or both. The default value of this attribute is date.
* The datestyle and timestyle attributes indicate how to format the date and time information respectively. Valid styles include default, short, medium, long, and full.
* The pattern attribute is used to specify custom styles, instead of built-in styles.
* If the VaR attribute is specified, the string value containing the formatted date is assigned to the specified variable.

<FMT: parsedate>: Used to parse the date and time values (data input)
* The type, datestyle, timestyle, pattern, and timezone attributes play the same role on <FMT: parsedate> and <FMT: formatdate>,
The difference is that for the former, they control the parsing of date values rather than displaying them.

* The parselocale attribute is used to specify a language environment. The value of the tag is parsed based on the language environment. It should be the name of the language environment or an instance of the locale class.

* For production code, it is best to process the verification and conversion of text input by the backend code (such as servlet), rather than the JSP custom tag.
 
5. digit mark
<FMT: formatnumber>: used to display digital data, including currency and percentage, in a language-specific manner. The operation is determined by the language environment,

* The value attribute is required. It is used to specify the value to be formatted.

* The value of the type attribute should be number, currency, or percentage, and specify the type of value to be formatted.
When the value of the type attribute is currency, the currencycode attribute can be used to explicitly specify the currency unit of the displayed value.

* The pattern attribute takes precedence over the type attribute and allows more precise formatting of values following the java. Text. decimalformat pattern conventions.

* The maxintegerdigits, minintegerdigits, maxfractiondigits, and minfractiondigits attributes are used to control the number of valid numbers displayed before and after the decimal point.
These attributes must be integer values.
* The groupingused attribute has a Boolean value and determines whether to group digits before the decimal point.


<FMT: parsedate>:
* The integeronly attribute indicates whether to parse only the integer part of the given value. If the value of this attribute is true, ignore any number following the decimal point in the string to be parsed. The default value of this attribute is false.

* Parsing data is not a very suitable task for presentation layer. If the parsing and validation data is implemented as part of the application's business logic, software maintenance will be simplified.

6. Message tag
<FMT: Message>: localized text.

* This operation uses the functions provided by the java. Text. messageformat class. Therefore, you can replace parameterized values with such text messages to dynamically customize localized content.

* Only the key attribute is required. The value of the key attribute is used to determine which messages are to be displayed in the resource bundle.
* Var attribute. The text message generated by the tag is assigned to the specified variable instead of the JSP page.
* <FMT: param> indicates the value attribute to provide parameterized values of text messages.

<FMT: setbundle>: The operation sets a default resource bundle for <FMT: Message> to be used in a specific scope,

* The basename attribute is required. It identifies the resource bundle set as the default value.
* The value of the basename attribute should not contain any localized suffixes or file extensions.
* The optional scope attribute specifies the JSP scope applied by the default resource bundle settings. If this attribute is not explicitly specified, it is assumed to be page scope.

* If an optional var attribute is specified, the resource bundle identified by the basename attribute is assigned to the variable named by the attribute.
In this case, the scope attribute specifies the scope of the variable; the default resource is not assigned to the corresponding JSP scope.

<FMT: bundle>: Specifies the resource bundle used for all and any <FMT: Message> operations nested in the TAG body content.
* Only the basename attribute is required. You can use the optional prefix attribute to specify the default prefix for the key values of any nested <FMT: Message> operation.

7. Use the JDK tool native2asci.exe to convert the code under the JDK/bin directory:

* The resource bundle used to store language-specific messages is in the form of class or feature files. These class or feature files comply with the standard naming conventions, in this naming convention, names and language environment names are combined.

Native2ascii [-reverse] [-encoding] [inputfile [outputfile]
 
Conversion: To: Unicode
Native2ascii-encoding gb2312 source. properties target. Properties

Reverse: reverse Unicode to specified code
Native2ascii-reverse-encoding big5 source22.properties target2.properties

Example: native2ascii-encoding gb2312 E:/Apache/zh_cn.txt E:/zh_cn.txt

V. XML library
 
1. As enterprise applications are increasingly dependent on XML, XML-format data is prioritized for information exchange.
The XML processing tag Library provides programmers with basic operations on XML format files. There are 10 tags in the tag library, which are divided into three categories:
XML Core labels: <X: parse>, <X: Out>, and <X: Set>.
XML Flow Control labels: <X: If>, <X: Choose>, <X: When>, <X: otherwise>, and <X: foreach>.
XML Conversion labels: <X: Transform> and <X: param>.

2, <X: parse>: tag is the core of the tag library for parsing XML files.

<X: parse> label attributes and descriptions
Attribute description
The content of the DOC source XML. The content of this attribute should be of the string type or Java. Io. Reader instance. It can be replaced by the XML Attribute, but is not recommended.
VaR stores the parsed XML in the variable specified by this attribute, and other labels in the XML processing tag library can be obtained from this variable if you want to retrieve the content in XML (optional)
Scope variable scope (optional)
Vardom specifies that the stored variable is of the org. W3C. Dom. Document Interface type (optional)
Scope of the action of the scopedom org. W3C. Dom. Document Interface Type Variable (optional)
Systemid defines a URI that will be used in an XML file to access other resource files (optional)
Filter: This attribute must be an instance of the org. xml. Sax. xmlfilter class. You can use the El expression to pass in and filter the XML file to obtain the desired part (optional)

Among them, VAR, scope, vardom, and scopedom should not appear at the same time, but should be regarded as two versions. Both variables can be used by other labels in the XML processing tag library.
<X: parse> labels are rarely used independently. They generally work together with other labels in the XML processing tag library. The following is an example.
First, a simple XML file is provided, which will be parsed. The XML file name is samplexml. xml.
<? XML version = "1.0" encoding = "UTF-8"?>
<XML-body>
<Name> RW </Name>
& Lt; password & gt; 123456 & lt;/password & gt;
<Age> 28 </age>
<Books>
<Book> book1 </book>
<Book> book2 </book>
<Book> book3 </book>
</Books>
</XML-body>

Tag Library:
<C: Import Var = "xmlfile" url = "http: // localhost: 8080/booksamplejstl/samplexml. xml"/>
<X: parse Var = "xmlfilevalue" Doc = "$ {xmlfile}"/>
In this example, the <C: Import> label is used to read the XML file. The <C: Import> label stores the content of the source XML file in the "xmlfile" variable. <X: parse> the tag parses "samplexml" based on the value of the "xmlfile" variable. XML ".

3, <X: Out>: used to display XML content
<X: Out> the tag retrieves the required XML file content from the variable saved after the <X: parse> tag is parsed and displayed on the page. This label is implemented through the XPath Technology (a technology used to locate XML elements. To use the <X: Out> label, the xalan-J jar package must be saved under WEB-INF/lib. Its Attributes and descriptions are shown in table 9.13:
 
<X: Out> label attributes and descriptions
Attribute description
Select XPath expression
When a special character such as '<, >,&,', 'appears in the obtained result string, it is replaced by an escape character.

The <X: Out> tag must work with the <X: parse> tag. The following is an example.
<C: Import Var = "xmlfile" url = "http: // localhost: 8080/booksamplejstl/samplexml. xml"/>
<X: parse Var = "xmlfilevalue" Doc = "$ {xmlfile}"/>
Name: <X: Out select = "$ xmlfilevalue/XML-body/Name"/> <br>
Password: <X: Out select = "$ xmlfilevalue/XML-body/password"/> <br>
Age: <X: Out select = "$ xmlfilevalue/XML-body/age"/> <br>

The xmlfilevalue variable after reading the XML file and parsing it will start with "$" as the XPath expression. The expression in the SELECT statement will obtain the object content from each sub-element under the XML-body root element.
 
The content of the "samplexml. xml" file is displayed.
Name: RW
Password: 123456
Age: 28

4, <X: Set>: used to save XML content.

<X: Set> A tag allows you to save the object content or attributes of an element in the source XML to a variable. The implementation of the tag also relies on the XPath technology.
 
<X: Set> label attributes and descriptions
Attribute description
Select XPath expression
Name of the variable in which var saves the result
Scope variable scope (optional)

<X: Set> the variable saved by the VaR of the tag is determined by the result of xpath. The following is an example.
<C: Import Var = "xmlfile" url = "http: // localhost: 8080/booksamplejstl/samplexml. xml"/>
<X: parse Var = "xmlfilevalue" Doc = "$ {xmlfile}"/>
<X: Set select = "$ xmlfilevalue/XML-body/Name" Var = "thisname"/>
Here, the content of the XML name element is saved to the variable "thisname.

5, <X: If>: used for judgment

<X: If> the tag allows the result of the Boolean () function of xpath to determine whether to display the content contained in the tag.
The attributes of the <X: If> label are the same as those of the <X: Set> label, but the result of VaR can only be of the boolean type.

6. <X: Choose>, <X: When>, and <X: otherwise>: used for complex judgment.

This group of tags will be used together to provide the "If elseif" Statement function.
<X: Choose> A tag has no attributes and can be considered as a parent tag. <X: When> and <X: otherwise> are used as sub-tags.
<X: When> A tag is equivalent to an "if" statement. It contains a select attribute, which is an XPATH judgment expression.
<X: otherwise> A tag has no attributes. It is equivalent to an "else" statement.

7, <X: foreach>: Used to loop XML elements.

<X: foreach> is the cyclic control label for the same name element in the XML file.

<X: Set> label attributes and descriptions
Attribute description
Select XPath expression. The result is a set that will be cyclic (optional)
Begin start condition (optional)
End end condition (optional)
Step of a step loop. The default value is 1 (optional)
The variable name of the object in which var loops are made, indicating an object in the result set of the XPath expression (optional)
Variable for varstatus to show loop status (optional)

The following is an example.
<X: foreach select = "$ xmlfilevalue/XML-body/books/book" Var = "book">
$ {Book}
</X: foreach>

In this example, multiple sub-book elements stored in the books element in XML are read cyclically.

8, <X: Transform>: format the XML display data.
<X: Transform> the label allows you to format the display data on the page using XSLT (a language used to convert the XML format.

<X: Transform> label attributes and descriptions
Attribute description
The content of the DOC source XML. The content of this attribute should be string, Java. io. reader, javax. XML. transform. source, org. w3C. dom. document instance, or from the <X: parse> and <X: Set> labels. Can be replaced by XML attributes, but is not recommended (optional)
XSLT source XSLT content. The content of this attribute should be string, java. Io. Reader, javax. xml. Transform. Source instance (optional)
Docsystemid defines a URI that will be used in an XML file to access other resource files. It can be replaced by the XML systemid attribute, but is not recommended (optional)
Xsltsystemid defines a URI that will be used in the XSLT file to access other resource files (optional)
VaR saves the formatted XML file to the variable specified by this attribute. The saved variable is of the org. W3C. Dom. Document Interface type (optional)
Scope variable scope (optional)
Result: Save the variable of the conversion result. The saved variable is an instance of the javax. xml. Transform. Result type (optional)

The following is an example:
<C: Import Var = "xmlfile" url = "http: // localhost: 8080/booksamplejstl/samplexml. xml"/>
<C: Set Var = "ttdoc">
<? XML version = "1.0"?>
<XSL: stylesheet xmlns: XSL = "http://www.w3.org/1999/XSL/Transform" version = "1.0">
<XSL: template match = "/">
<XSL: Apply-templates/>
</XSL: Template>
<XSL: template match = "XML-Body">
<HTML>
<Head> <Body marginheight = "0" marginwidth = "0" topmargin = "0" leftmargin = "0">
<H2>
Username:
<XSL: value-of select = "name"/>
</H2>
<H2>
Password:
<XSL: value-of select = "password"/>
</H2>
<H2>
Age:
<XSL: value-of select = "Age"/>
</H2>
</Body>
</Html>
</XSL: Template>
</XSL: stylesheet>
</C: Set>
<X: Transform XSLT = "$ {javastdoc}" Doc = "$ {xmlfile}"/>

In this example, the data information stored in the XML file is saved in "xmlfile" using <C: Import>, and then an XSLT source is saved to "ttdoc" using the <C: Set> tag ", finally, the data in the XML file is formatted using <X: Transform> and displayed on the page.

9. The <X: param> label used for parameter transfer.
<X: param> labels are used to pass the required parameters when formatting XML. Its Attributes and descriptions are the same as those of the <C: param> label.

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.