JSTL improved JSP to simplify the process of Web page implementation (4)

Source: Internet
Author: User
Tags foreach date format connection pooling expression sql error xml attribute xpath
js| Process | Web page format TAG library: format actions

If you have already used Java DateFormat and NumberFormat classes, the methods used in the following markup should look familiar, because the Jstl formatting actions are built on top of those classes. These Java classes generally provide a format () function that converts a Java type into a formatted string and creates a Java object corresponding to that string.

The Fmt:formatnumber action has a Value property and a pattern attribute. The Value property is an EL expression or variable that is similar to the 黺 Alue property that we blow down sodium lu liling. The Pattern property is the same as that defined in the NumberFormat class. The following actions send a formatted string to the output of the JSP page:
 <fmt:formatnumber value= "1000.001" pattern= "#, #00.0#"/>
In this fmt:formatnumber action, we use the type attribute to specify that the format we want to format is a currency value. We save the formatted result in a variable named dollars. In an American locale class, the following program generates a string $3456.79 (note that it will round up the currency values used): 
    <fmt:formatnumber value= "3456.789" type= "Currency" var= "Dollars"/>
The possible values for the type attribute above include currency, number, and percent.

In the example, we use an alternative method--a text string that uses a formatted field (currency, per type attribute) that is included in the Value property. And parse it to get a number. The result is stored in a variable specified by the var attribute. Although this property is optional, it is often used. In addition, the parsed value is sent to the page output: 


<fmt:parsenumber value= "${currencyinput}" type= "Currency" var= "Parsednumber"/>fmt:formatdate action has a Value property, A Format property, a property that points to a format class that handles formatting 

(typically, such as java.util.Date): <jsp:usebean id= "Now" class= "Java.util.Date"/><FMT: FormatDate value= "${now}" timestyle= "Long" datestyle= "Long"/>

<fmt:parseNumber value="${currencyInput}" type="currency" var="parsedNumber"/> The fmt:formatDate action has a value attribute, a format attribute,

 and a property that points to a processed class (typical , such as java.util.Date): <jsp:useBean id="now" class="java.util.Date" /> <fmt:formatDate value="${now}" timeStyle="long" dateStyle="long "/>


Like the number format, the JSTL page provides a mechanism for parsing a string that represents a date, and that goes into date objects:
<fmt:parsedate value= "${dateinput}" pattern= "MM dd, YYYY"/>
See the Java.util.DateFormat class for more detailed information about how to handle formatting and schemas.

Format Tag Library: internationalization actions

A key point in Java localization is the ResourceBundle class. Jstl action allows you to use this kind of simple work. This example uses the Fmt:bundle action to get a resourcebundle action corresponding to the current locale and fmt:message actions to view the localized strings in the resource bundle:
<fmt:bundle basename= "Mybundle" ><%--use values in Mybundle--%><fmt:message key= "Introduction" >   <fmt:param value= "${loginname}"/>   

<fmt:param value= "${logincount}"/></fmt:message> <fmt:formatdate value= "${now}" var= "Parseddate"/></fmt:bundle>
<fmt:bundle basename="myBundle"> <%-- Use values in myBundle --%> <fmt:message key="Introduction"> <fmt:param value="${loginName}"/> 

<fmt:param value="${loginCount}"/> </fmt:message> <fmt:formatDate value="${now}" var="parsedDate"/> </fmt:bundle>


Often, the fmt:message action simply looks at the string corresponding to a keyword. In the above example, the string in ResourceBundle contains a placeholder that replaces two values. These values are defined in the Fmt:param action, which is like the method used by the Java Messageformat class.

There are similar actions that specify a time zone that can be applied to anything computed in the body of the tag:
 <fmt:timezone value= "Sometimezone" ><!--actions in the context would be evaluated using Sometimezone-->  </fmt:timeZone
The above Fmt:bundle and fmt:timezone actions have corresponding Fmt:setbundle and fmt:settimezone actions respectively. These actions add optional scope properties, so you can use these actions to set a resource bundle or a time zone in any scope equivalent to the scope of the application.

If you work with a non-European locale, you may have to worry about coding, JSTL support fmt:requestencoding action code.

SQL Tag Library

JSTL allows easy integration of the database. However, it is noteworthy that there are some restrictions on the execution of Jstl outside the sandbox. The main problem relates to connection pooling. Establishing and maintaining a connection to a database is very resource-intensive. The JSTL SQL action allows many database connections to be established, usually at least one for each user. Therefore, JSTL SQL tags are significant for prototypes or Low-volume, web-based applications. But it is not suitable for large-scale applications. A scalable product application typically handles database access within one page, such as hiding database access and processing details like connection pooling. However, there are ways to allow you to implement connection pooling and use a bit of custom code to JSTL SQL actions
Let's look at some simple examples. These examples use the JSTL tag from the SQL library. If you are familiar with the basics of SQL, you should be able to adapt these examples to your application.

In the following program fragment, we set up a connection to a database, select a set of order items that match one order ID, and display the Item property in a table: 


<sql:setdatasource      driver= "com.cheapDrivers.jdbcDriver"      url= "jdbc:cheapdrivers:."      User= "Guest"      password= "password"      var= "DataSource"/>

<sql:query var= "OrderItems" datasource= "${" DataSource} ">select * from Itemswhere order_id = <cout value= ' ${orderid} '/> ORDER by price</sql:query>

 <table><c:foreach var= "Row" items= "${orderitems.rows} ><tr><td><c:out value=" ${ Row.itemname} "/></td><td><c:out value=" ${row.price} "/></td><td>

<c:out value= "${row.weight}"/></td></tr></c:foreach></table>

<sql:setDataSource driver="com.cheapDrivers.jdbcDriver" url="jdbc:cheapDrivers:." user="guest" password="password" var="dataSource" /> 

<sql:query var="orderItems" dataSource="${dataSource}"> SELECT * FROM items WHERE order_id = <cout value="${orderID}"/> ORDER BY price </sql:query> 

<table> <c:forEach var="row" items="${orderItems.rows}"> <tr> <td><c:out value="${row.itemName}"/></td> <td><c:out value="${row.price}"/></td>

 <td><c:out value="${row.weight}"/></td> </tr> </c:forEach> </table>


In the next example, I'll explain how Jstl supports database transactions, in which many operations that contain multiple changes to a table must be all or nothing: if a problem arises, the change must be empty. In the following example, the Sql:update action is contained within a sql:transaction action, and if there is any SQL error in the transaction, all operations performed within the scope of the transaction will have to be redone.

The naming of sql:update actions is a bit misleading: In addition to SQL update, Sql:update also supports inserts and deletes, even SQL CREATE. In fact, it supports any SQL operation that does not produce a result. In the following example, Sql:update performs an update action by inserting a variable value into a PreparedStatement. In this code snippet, we transfer money between two accounts (a classic example of something that needs to be prepackaged in a transaction): 


<sql:transaction datasource= "${datasource}" ><sql:update>update Accountset account_balance =account_ Balance-? WHERE Accountno =?

 <sql:param value= "${transferamount}"/><sql:param value= "${sourceaccount}"/></sql: Update><sql:update>update accountset account_balance =account_balance +? WHERE Accountno =? 

<sql:param value= "${transferamount}"/><sql:param value= "${destaccount}"/></sql: Update></sql:transaction>
<sql:transaction dataSource="${dataSource}"> <sql:update> UPDATE account SET account_balance =account_balance -? WHERE accountNo = ? 

<sql:param value="${transferAmount}"/> <sql:param value="${sourceAccount}"/> </sql:update> <sql:update> UPDATE account SET account_balance =account_balance +? WHERE accountNo = ? 

<sql:param value="${transferAmount}"/> <sql:param value="${destAccount}"/> </sql:update> </sql:transactio


XML Tag Library

Using a standard XML tag library, the complete processing you can do, particularly the processing of an extensible Single Language Transformation Description (XSLT), is a good topic for another article. Below I will cover enough to let you start the knowledge.

The XML support in Jstl follows the XPath specification. One of the important functions of XPath is to provide a clear syntax for accessing information that is well-known for XML hierarchies. Perhaps the easiest way to see how each one works is to see how we use the tags from a fragment of a real Jstl page: 


!--Find and Parse we XML document (somewhere on the WWW)--><c:import url= "Http://www.cheapstuff.com/orderStatus?i d=2435 "var=" xml/>

<x:parse xml= "${xml}" var= "Doc"/><!--access XML data via XPath expressions--><x:o UT select= "$doc/name"/><x:out select= "$doc/shippingaddress"/>

<x:out select= "$doc/deliverydate"/> <!--Set a scoped variable--><x:set var= "CustName" scope= "Request" select= "$doc/name"/>
!-- Find and parse our XML document (somewhere on the WWW) --> <c:import url="http://www.cheapstuff.com/orderStatus?id=2435" var="xml"/>

 <x:parse xml="${xml}" var="doc"/> <!-- access XML data via XPath expressions --> <x:out select="$doc/name"/> <x:out select="$doc/shippingAddress"/>

 <x:out select="$doc/deliveryDate"/> <!-- Set a scoped variable --> <x:set var="custName" scope="request" select="$doc/name"/


In the above input and parsing actions, we loaded and parsed a specified XML document into a variable doc. In each of the x:out actions above, we used an XPath expression to access the elements of the parsed XML document and send the results to the JSP page output.

The above set expression evaluates an XPath expression and enters the result into a scoped variable (in the example above, it refers to the scope of a request).

X:out and X:set actions can output a jsptagexception. If they don't succeed (most likely because XPath expressions point to nonexistent tags), your page, like in all other cases, should intelligently handle these exceptions (either through traditional JSP errorpage directives or using jstl c:catch actions),

Jstl easily handles XSLT transformations. In the following demo page, we use the X:transform action from the XML tag library to create a formatted page from the XML source document with an XSLT stylesheet. The most important attribute of the X:transform action is the XML and XSLT attributes, in the following example we set up an XSLT attribute from the variable we initialized on the same page; we also set the XML attribute in the body of the action. The action defaults to the X:transform action.

By default, the result of the conversion is sent to the page output; You can also save the results to a variable with the X:var attribute:


<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jstl/xml" prefix="x" %> <c:set var="xsltSource">

 <?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="music"> <html> <head></head> <body marginheight="0" marginwidth="0" topmargin="0" leftmargin="0"> <table cellpadding="0" cellspacing="0" border="1" bgcolor="#ffffff">

 <tr> <td><STRONG>Artist</STRONG></td> <td><STRONG>Album</STRONG></td> <td><STRONG>Year</STRONG></td> <td><STRONG>Genre</STRONG></td> </tr> 

<!---Set up for loop to collect all the artist information //--> <!-- <xsl:for-each select="./*[name()= artists ]"> --> <xsl:for-each select="artists"> <tr> 

<td><xsl:value-of select="artist"/></td> <td><xsl:value-of select="album"/></td> <td><xsl:value-of select="year"/></td> <td><xsl:value-of select="genre"/></td> 

</tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> </c:set> <x:transform xslt="${xsltSource}" > <music> <artists> <artist>Jonny B</artist> 

<album>Feedback and Distortion</album> <year>2001</year> <genre>Rock</genre> </artists> <artists> <artist>Harmony s Nieces</artist> <album>Sappy Pop Ballads</album> 

<year>2002</year> <genre>Pop</genre> </artists> </music> </x:transform


You can also use the C:import action to define an additional source document and stylesheet, as shown in the code snippet for this demo:


 <c:import var= "${xmlsource}" url= "${somedocumenturl}"/><c:import var= "${xsltsource}" url= "${" Anotherdocumenturl} "/><x:transform xml=" ${xmlsource} "xslt=" ${xsltsource} ">
<c:import var="${xmlSource}" url="${someDocumentURL}" /> <c:import var="${xsltSource}" url="${anotherDocumentURL}" /> <x:transform xml="${xmlSource}" xslt="${xsltSource}" >


Conclusion 
 
At this point, you should have a good understanding of JSTL, its four standard tag libraries, and how it makes web development easier. Now you start writing some jstl! 
 

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.