• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Jstl Guide
 

Jstl Guide

on

  • 5,481 views

JSTL Tutorial

JSTL Tutorial

Statistics

Views

Total Views
5,481
Views on SlideShare
5,392
Embed Views
89

Actions

Likes
3
Downloads
213
Comments
0

2 Embeds 89

http://wiki.bcmoney-mobiletv.com 83
http://www.slideshare.net 6

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Avoid conflicts between jar versions (XML, JDBC etc’) <br /> Eases Web page Development <br /> Open Source Extensions <br /> Easy to read and maintain <br /> Reuse Valuable Components and Reusable standard tags <br /> Eases packaging of the application - Searches for the tld’s in several places (tld, META-INF) <br /> Eases Database Access <br /> As a matter of practice, a JSP page should be a view page, it should not have Java code embedded in scriptlets. This aids in separation of concerns. A JSP page can use JSTL elements for common tasks like conditional processing, database access, internationalization and more. <br /> Database access can be controlled using an data-sources.xml file <br /> The idea is that once the libraries are installed correctly, the page is dead-simple to put together. <br />
  • It is important to have a DOCTYPE element to a <br />
  • JSTL is not a general purpose programming language. <br /> Is simply a data access language, which makes it possible to easily access application data. <br /> JSTL allows page authors to access an object using a simplified syntax. <br /> &lt;someTags:aTag attribute=&quot;${aName}&quot;&gt; <br /> &lt;someTags.aTag attribute=&quot;${aCustomer.address.country}&quot;&gt; <br />
  • As a property of an object, using the dot (.) operator <br /> As named array element using the bracket [&apos;name&apos;] operator. <br /> E.g. ${data} – scoped variable data. <br /> The dot (.) operator is used to retrieve a named property. <br /> ${customer.name} <br /> The bracket operator ([]) can be used to retrieve a named property. <br /> ${customer[&quot;name&quot;]}. <br /> ${customers[0]} <br /> ${customer.name} is equivalent to ${customer[&quot;name&quot;]}. <br /> All EL expressions must be enclosed between ${ and }. <br /> EL evaluates an identifier by using PageContext.findAttribute(String). <br />
  • Supports output, manipulation of scoped variables, conditional logic, loops, URL manipulation, and error handling. <br />
  • &lt;c:out&gt; - writing data <br /> &lt;c:set&gt; - set the value of a scoped attribute <br /> &lt;c:remove&gt; - remove a scoped variable. <br /> &lt;c:catch&gt; - handling errors. See the next setion for an example <br />
  • jsp include action and directive does not allow include of remote resources <br />
  • XML is becoming increasingly important to page authors, and the JSTL provides XML actions that address the basic needs of those developers. The XML actions can be divided into core, control flow, and transformation actions. The XML core actions are similar to those provided in the core actions discussed above, and include &lt;x:out&gt;, &lt;x:set&gt;, and &lt;x:parse&gt;. The main difference between the core actions discussed above and the XML core actions is that XML actions support XPath expressions, while the core actions do not. As a matter of fact, the XML actions are based on XPath expressions. If you&apos;re unfamiliar with XPath, it&apos;s a language for defining parts of an XML document; XPath uses path expressions to identify nodes in an XML document. <br />
  • XML Core - similar to the basic core actions <br /> &lt;x:out&gt; <br /> &lt;x:set&gt; <br /> and &lt;x:parse&gt; <br /> XML Control Flow <br />
  • You can implement an if/then/else clause using the &lt;x:choose&gt; action, which selects one among a number of possible alternatives. It consists of a sequence of &lt;x:when&gt; elements, followed by an optional &lt;x:otherwise&gt;. Each &lt;x:when&gt; element has a single attribute, select, that specifies an XPath expression. When a &lt;x:choose&gt; element is processed, each of the &lt;x:when&gt; elements has its expressions evaluated in turn. Only the body of the first &lt;x:when&gt; element (whose result is true) is rendered. If none of the test conditions of nested tags evaluates to true, the body of the &lt;x:otherwise&gt; tag is evaluated, if present. <br /> Here is an example: <br /> &lt;x:parse xml=&quot;${xmldoc}&quot; var=&quot;output&quot;/&gt; <br /> &lt;x:choose&gt; <br /> &lt;x:when select=&quot;$output/portfolio/stock[price &gt; &apos;70&apos;]&quot;&gt; <br /> You still have stocks worth over $70. <br /> &lt;/x:when&gt; <br /> &lt;x:otherwise&gt; <br /> You have no stocks worth over $70. <br /> &lt;/x:otherwise&gt; <br /> &lt;/x:choose&gt; <br /> ----------------------------------------------------------- <br /> The &lt;x:forEach&gt; action evaluates the given XPath expression, and iterates over the result. <br /> E.g. Print stock information from an XML document. <br /> &lt;x:parse xml=&quot;${xmldoc}&quot; var=&quot;output&quot;/&gt; <br /> &lt;x:forEach select=&quot;$output/portfolio/stock&quot; var=&quot;item&quot;&gt; <br /> &lt;x:out select=&quot;symbol&quot;/&gt; <br /> &lt;x:out select=&quot;name&quot;/&gt; <br /> &lt;x:out select=&quot;price&quot;/&gt; <br /> &lt;/x:forEach&gt; <br />
  • parses an XML document, then selects (using an XPath expression) the stock with the symbol SUNW &lt;x:parse xml=&quot;${xmldoc}&quot; var=&quot;output&quot;/&gt; <br /> &lt;x:if select=&quot;$output/portfolio/stock[symbol = &apos;SUNW&apos;]&quot;&gt; <br /> You still have Microsystems Stocks! <br /> &lt;/x:if&gt; <br /> -------------------------------------------------------------------- <br /> &lt;x:forEach select=&quot;$output/portfolio/stock&quot;&gt; <br /> &lt;x:out select=&quot;price&quot;/&gt; <br /> &lt;/x:forEach&gt; <br /> -------------------------------------------------------------------- <br />
  • Many web applications use XSLT stylesheets to transform XML within JSP pages, and the JSTL supports this. The XML document to be transformed, as well as the XSLT stylesheet to be used, can be retrieved from a relative, absolute, or remote URL. The result of the transformation is written to the page. As an example, the stocks.xml document shown in Code Sample 2 (which is located at a remote web server) is transformed using the XSLT stylesheet (stocks.xsl) shown in Code Sample 4 but fetched from a local web server: <br /> Code Sample 4: stocks.xsl <br /> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;xsl:stylesheet xmlns:xsl= &quot;http://www.w3.org/1999/XSL/Transform&quot; version=&quot;1.0&quot;&gt; &lt;xsl:output method=&quot;html&quot; indent=&quot;yes&quot;/&gt; &lt;xsl:template match=&quot;/&quot;&gt; &lt;html&gt; &lt;body&gt; &lt;xsl:apply-templates/&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;xsl:template match=&quot;portfolio&quot;&gt; &lt;table border=&quot;2&quot; width=&quot;50%&quot;&gt; &lt;xsl:for-each select=&quot;stock&quot;&gt; &lt;tr&gt; &lt;td&gt; &lt;i&gt;&lt;xsl:value-of select=&quot;symbol&quot;/&gt;&lt;/i&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select=&quot;name&quot;/&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select=&quot;price&quot;/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/xsl:for-each&gt; &lt;/table&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; The following example, xml-ex3.jsp (shown in Code Sample 5) demonstrates how to transform an XML document located on a remote web server using the stocks.xsl stylesheet shown in Code Sample 4. <br /> Code Sample 5: xml-ex3.jsp <br /> &lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %&gt; &lt;%@ taglib prefix=&quot;x&quot; uri=&quot;http://java.sun.com/jstl/xml&quot; %&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;JSTL: Importing XML Document&lt;/title&gt; &lt;/head&gt; &lt;body bgcolor=&quot;#FFFFCC&quot;&gt; &lt;h3&gt;Transforming stocks.xml into HTML using stocks.xsl&lt;/h3&gt; &lt;c:import url=&quot;http://www.javacourses.com/stocks.xml&quot; var=&quot;xmldocument&quot;/&gt; &lt;c:import url=&quot;./stocks.xsl&quot; var=&quot;xslt&quot;/&gt; &lt;x:transform xml=&quot;${xmldocument}&quot; xslt=&quot;${xslt}&quot;/&gt; &lt;/body&gt; &lt;/html&gt; When you load xml-ex3.jsp, you should see something in the browser similar to Figure 3. <br /> Figure 3: Transforming an XML document using an XSLT stylesheet <br />
  • Many web applications need to access relational databases as the source of dynamic <br /> data for their presentation layer. While it is generally preferred to have database <br /> operations handled within the business logic of a web application designed with an <br /> MVC architecture, there are situations where page authors require this capability <br /> within their JSP pages (e.g. prototyping/testing, small scale/simple applications, <br /> lack of developer resources). <br /> The JSTL SQL actions provide the basic capabilities to easily interact with relational <br /> databases. <br />
  • The JSTL SQL actions allow page authors to: <br /> ■ Perform database queries (select) <br /> ■ Easily access query results <br /> ■ Perform database updates (insert, update, delete) <br /> ■ Group several database operations into a transaction <br />
  • SQL actions operate on a data source, as defined by the Java class <br /> javax.sql.DataSource. A DataSource object provides connections to the <br /> physical data source it represents. Within the context of a Connection retrieved <br /> from the DataSource, SQL statements are executed and results are returned. <br /> A data source can be specified explicitly via the dataSource attribute in SQL <br /> actions, or it can be totally transparent to a page author by taking advantage of the <br /> data source configuration setting (javax.servlet.jsp.jstl.sql.dataSource). <br /> There are two ways a data source can be specified as a string. <br /> The first way is through a JNDI relative path, assuming a container supporting <br /> JNDI. For example, with the absolute JNDI resource path java:comp/env/jdbc/ <br /> myDatabase, the JNDI relative path to the data source resource would simply be <br /> jdbc/myDatabase, given that java:comp/env is the standard JNDI root for a <br /> J2EE application. <br /> The second way is by specifying the parameters needed by the JDBC <br /> DriverManager class, using the following syntax (see Section 10.6 for details on the <br /> JDBC parameters) <br /> url[,[driver][,[user][,password]]] <br /> For example, <br /> jdbc:mysql://localhost/,org.gjt.mm.mysql.Driver <br /> where the database has been setup for access without any username or password. If <br /> the ‘,’ character occurs in any of the JDBC parameters, it can be escaped by ‘’. The <br /> character ‘’ itself can be escaped in the same way. <br /> While the JDBC DriverManager class provides a low cost way to use SQL actions, <br /> it is not recommended to use it other than for prototyping purposes because it does <br /> not provide connection management features one can expect from a properly <br /> designed DataSource object. <br />
  • The most common use of the database actions is to query a database and display the <br /> results of the query. <br /> The following sample code selects all customers from China from the customers <br /> table in the database, orders them by last name, and finally displays their last name, <br /> first name, and address in an HTML table. <br /> &lt;sql:query var=&quot;customers&quot; dataSource=&quot;${dataSource}&quot;&gt; <br /> SELECT * FROM customers <br /> WHERE country = ’China’ <br /> ORDER BY lastname <br /> &lt;/sql:query&gt; <br /> &lt;table&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${customers.rows}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.lastName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.firstName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.address}&quot;/&gt;&lt;/td&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br /> This next example shows a generic way to display the results of a query with <br /> column names as headers: <br /> &lt;table&gt; <br /> &lt;!-- column headers --&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=”columnName” items=”${result.columnNames}”&gt; <br /> &lt;th&gt;&lt;c:out value=&quot;${columnName}&quot;/&gt;&lt;/th&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;!-- column data --&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${result.rowsByIndex}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=&quot;column&quot; items=&quot;${row}&quot;&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${column}&quot;/&gt;&lt;/td&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br />
  • The most common use of the database actions is to query a database and display the <br /> results of the query. <br /> The following sample code selects all customers from China from the customers <br /> table in the database, orders them by last name, and finally displays their last name, <br /> first name, and address in an HTML table. <br /> &lt;sql:query var=&quot;customers&quot; dataSource=&quot;${dataSource}&quot;&gt; <br /> SELECT * FROM customers <br /> WHERE country = ’China’ <br /> ORDER BY lastname <br /> &lt;/sql:query&gt; <br /> &lt;table&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${customers.rows}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.lastName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.firstName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.address}&quot;/&gt;&lt;/td&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br /> This next example shows a generic way to display the results of a query with <br /> column names as headers: <br /> &lt;table&gt; <br /> &lt;!-- column headers --&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=”columnName” items=”${result.columnNames}”&gt; <br /> &lt;th&gt;&lt;c:out value=&quot;${columnName}&quot;/&gt;&lt;/th&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;!-- column data --&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${result.rowsByIndex}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=&quot;column&quot; items=&quot;${row}&quot;&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${column}&quot;/&gt;&lt;/td&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br />
  • The most common use of the database actions is to query a database and display the <br /> results of the query. <br /> The following sample code selects all customers from China from the customers <br /> table in the database, orders them by last name, and finally displays their last name, <br /> first name, and address in an HTML table. <br /> &lt;sql:query var=&quot;customers&quot; dataSource=&quot;${dataSource}&quot;&gt; <br /> SELECT * FROM customers <br /> WHERE country = ’China’ <br /> ORDER BY lastname <br /> &lt;/sql:query&gt; <br /> &lt;table&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${customers.rows}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.lastName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.firstName}&quot;/&gt;&lt;/td&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${row.address}&quot;/&gt;&lt;/td&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br /> This next example shows a generic way to display the results of a query with <br /> column names as headers: <br /> &lt;table&gt; <br /> &lt;!-- column headers --&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=”columnName” items=”${result.columnNames}”&gt; <br /> &lt;th&gt;&lt;c:out value=&quot;${columnName}&quot;/&gt;&lt;/th&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;!-- column data --&gt; <br /> &lt;c:forEach var=&quot;row&quot; items=&quot;${result.rowsByIndex}&quot;&gt; <br /> &lt;tr&gt; <br /> &lt;c:forEach var=&quot;column&quot; items=&quot;${row}&quot;&gt; <br /> &lt;td&gt;&lt;c:out value=&quot;${column}&quot;/&gt;&lt;/td&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/tr&gt; <br /> &lt;/c:forEach&gt; <br /> &lt;/table&gt; <br />
  • Updating a Database <br /> The &lt;sql:update&gt; action updates a database. To ensure database integrity, several <br /> updates to a database may be grouped into a transaction by nesting the <br /> &lt;sql:update&gt; actions inside a &lt;sql:transaction&gt; action. <br /> For example, the following code transfers money between two accounts in one <br /> transaction: <br /> &lt;sql:transaction dataSource=&quot;${dataSource}&quot;&gt; <br /> &lt;sql:update&gt; <br /> UPDATE account <br /> SET Balance = Balance - ? <br /> WHERE accountNo = ? <br /> &lt;sql:param value=&quot;${transferAmount}&quot;/&gt; <br /> &lt;sql:param value=&quot;${accountFrom}&quot;/&gt; <br /> &lt;/sql:update&gt; <br /> &lt;sql:update&gt; <br /> UPDATE account <br /> SET Balance = Balance + ? <br /> WHERE accountNo = ? <br /> &lt;sql:param value=&quot;${transferAmount}&quot;/&gt; <br /> &lt;sql:param value=&quot;${accountTo}&quot;/&gt; <br /> &lt;/sql:update&gt; <br /> &lt;/sql:transaction&gt; <br />
  • Updating a Database <br /> The &lt;sql:update&gt; action updates a database. To ensure database integrity, several <br /> updates to a database may be grouped into a transaction by nesting the <br /> &lt;sql:update&gt; actions inside a &lt;sql:transaction&gt; action. <br /> For example, the following code transfers money between two accounts in one <br /> transaction: <br /> &lt;sql:transaction dataSource=&quot;${dataSource}&quot;&gt; <br /> &lt;sql:update&gt; <br /> UPDATE account <br /> SET Balance = Balance - ? <br /> WHERE accountNo = ? <br /> &lt;sql:param value=&quot;${transferAmount}&quot;/&gt; <br /> &lt;sql:param value=&quot;${accountFrom}&quot;/&gt; <br /> &lt;/sql:update&gt; <br /> &lt;sql:update&gt; <br /> UPDATE account <br /> SET Balance = Balance + ? <br /> WHERE accountNo = ? <br /> &lt;sql:param value=&quot;${transferAmount}&quot;/&gt; <br /> &lt;sql:param value=&quot;${accountTo}&quot;/&gt; <br /> &lt;/sql:update&gt; <br /> &lt;/sql:transaction&gt; <br />
  • SQL Statement Parameters <br /> The JSTL database actions support substituting parameter values for parameter <br /> markers (“?”) in SQL statements (as shown in the previous example). This form of <br /> parametric replacement is exposed by the SQLExecutionTag interface (see <br /> Section 10.10). <br /> The SQLExecutionTag interface is implemented by the tag handlers for <br /> &lt;sql:query&gt; and &lt;sql:update&gt;. It is exposed in order to support custom parameter <br /> actions. These custom actions may retrieve their parameters from any source and <br /> process them before substituting them for a parameter marker in the SQL statement <br /> of the enclosing SQLExecutionTag action. <br /> For example, a GUI front end may have a user enter a date as three separate fields <br /> (year, month, and day), and use this information in a database query. If the database <br /> table being accessed provides only a single column for the complete date, action <br /> &lt;acme:dateParam&gt; could assemble the three separate input parameters into one and <br /> pass it to the addSQLParameter() method of its enclosing SQLExecutionTag <br /> action: <br /> &lt;sql:update&gt; <br /> UPDATE PersonalInfo <br /> SET BirthDate = ? <br /> WHERE clientId = ? <br /> &lt;acme:dateParam year=&quot;${year}&quot; month=&quot;${month}&quot; day=&quot;${day}&quot;/&gt; <br /> &lt;sql:param value=”${clientId}”/&gt; <br /> &lt;/sql:update&gt; <br /> The JSTL formatting tags may be used to parse the string representation of dates and <br /> numbers into instances of java.util.Date and java.lang.Number, respectively, <br /> before supplying them to an enclosing SQLExecutionTag for parametric <br /> replacement: <br /> &lt;sql:update sql=&quot;${sqlUpdateStmt}” dataSource=&quot;${dataSource}&quot;&gt; <br /> &lt;fmt:parseDate var=&quot;myDate&quot; value=&quot;${someDate}”/&gt; <br /> &lt;sql:param value=&quot;${myDate}&quot;/&gt; <br /> &lt;/sql:update&gt; <br />
  • SQL Statement Parameters <br /> The JSTL database actions support substituting parameter values for parameter <br /> markers (“?”) in SQL statements (as shown in the previous example). This form of <br /> parametric replacement is exposed by the SQLExecutionTag interface (see <br /> Section 10.10). <br /> The SQLExecutionTag interface is implemented by the tag handlers for <br /> &lt;sql:query&gt; and &lt;sql:update&gt;. It is exposed in order to support custom parameter <br /> actions. These custom actions may retrieve their parameters from any source and <br /> process them before substituting them for a parameter marker in the SQL statement <br /> of the enclosing SQLExecutionTag action. <br /> For example, a GUI front end may have a user enter a date as three separate fields <br /> (year, month, and day), and use this information in a database query. If the database <br /> table being accessed provides only a single column for the complete date, action <br /> &lt;acme:dateParam&gt; could assemble the three separate input parameters into one and <br /> pass it to the addSQLParameter() method of its enclosing SQLExecutionTag <br /> action: <br /> &lt;sql:update&gt; <br /> UPDATE PersonalInfo <br /> SET BirthDate = ? <br /> WHERE clientId = ? <br /> &lt;acme:dateParam year=&quot;${year}&quot; month=&quot;${month}&quot; day=&quot;${day}&quot;/&gt; <br /> &lt;sql:param value=”${clientId}”/&gt; <br /> &lt;/sql:update&gt; <br /> The JSTL formatting tags may be used to parse the string representation of dates and <br /> numbers into instances of java.util.Date and java.lang.Number, respectively, <br /> before supplying them to an enclosing SQLExecutionTag for parametric <br /> replacement: <br /> &lt;sql:update sql=&quot;${sqlUpdateStmt}” dataSource=&quot;${dataSource}&quot;&gt; <br /> &lt;fmt:parseDate var=&quot;myDate&quot; value=&quot;${someDate}”/&gt; <br /> &lt;sql:param value=&quot;${myDate}&quot;/&gt; <br /> &lt;/sql:update&gt; <br />
  • Database Access <br /> This section describes the algorithm used by the SQL actions (&lt;sql:query&gt;, <br /> &lt;sql:update&gt;, &lt;sql:transaction&gt;) to access a database. <br /> Try to get a reference to a data source as follows: <br /> If the attribute dataSource is specified, use the value specified for that <br /> attribute as the data source. <br /> Otherwise, get the configuration setting associated with <br /> javax.servlet.jsp.jstl.sql.dataSource using Config.find() (see <br /> Section 2.8). Use the value found as the data source if it is not null. <br /> If a data source is obtained from the previous step: <br /> If it is a DataSource object, this is the data source used by the action to access <br /> the database. <br /> Otherwise, if it is a String: <br /> Assume this is a JNDI relative path and retrieve the data source from the <br /> container’s JNDI naming context by concatenating the specified relative path <br /> to the J2EE defined root (java:comp/env/). <br /> If the previous step fails (data source not found), assume the string specifies <br /> JDBC parameters using the syntax described in Section 10.1.1 and do as <br /> follows: <br /> If driver is specified, ensure it is loaded <br /> Access the named URL through the DriverManager class, using an <br /> empty string for user or password if they are not specified. <br /> If the previous step fails, throw an exception. <br /> Otherwise, throw an exception. <br /> An implementation need not create new objects each time a SQL action is called and <br /> the algorithm above does not yield a DataSource object directly; i.e when a JNDI <br /> path or parameters for the JDBC DriverManager class are used. It may reuse <br /> objects that it previously created for identical arguments. <br />
  • Developing and Using Functions <br /> The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). <br /> To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum. <br /> Code Sample 3: Compute.java <br /> package jsp2.examples.el; <br /> import java.util.*; <br /> public class Compute { <br /> public static int add(String x, String y) { <br /> int a = 0; <br /> int b = 0; <br /> try { <br /> a = Integer.parseInt(x); <br /> b = Integer.parseInt(y); <br /> } <br /> catch(Exception e) { <br /> } <br /> return a + b; <br /> } <br /> } <br /> Once this is successfully compiled using javac, the next step is to map the function&apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later. <br /> Code Sample 4: Function Descriptor <br /> &lt;function&gt; <br /> &lt;description&gt;add x and y&lt;/description&gt; <br /> &lt;name&gt;add&lt;/name&gt; <br /> &lt;function-class&gt;jsp2.examples.el.Compute &lt;/function-class&gt; <br /> &lt;function-signature&gt;int add(java.lang.String,java.lang.String) &lt;/function-signature&gt; <br /> &lt;/function&gt; <br /> Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &quot;Add Numbers&quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page. <br /> Code Sample 5: math.jsp <br /> &lt;%@ taglib prefix=&quot;my&quot; uri=&quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Functions&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H3&gt;Add Numbers&lt;/H3&gt; <br /> &lt;P&gt; <br /> &lt;FORM action=&quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&quot; method=&quot;GET&quot;&gt; <br /> X = &lt;input type=&quot;text&quot; name=&quot;x&quot; value=&quot;${param[&quot;x&quot;]}&quot;&gt; <br /> &lt;BR&gt; <br /> Y = &lt;input type=&quot;text&quot; name=&quot;y&quot; value=&quot;${param[&quot;y&quot;]}&quot;&gt; <br /> &lt;input type=&quot;submit&quot; value=&quot;Add Numbers&quot;&gt; <br /> &lt;/FORM&gt; <br /> &lt;P&gt; <br /> The sum is: ${my:add(param[&quot;x&quot;],param[&quot;y&quot;])} <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel <br /> Compile Compute.java using javac <br /> Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &lt;/function&gt; in the file and before &lt;/taglib&gt; <br /> Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the jsp file math.jsp from a web browser <br /> If all goes well, you should see something similar to Figure 3. <br /> Figure 3: Using Functions <br />
  • Developing and Using Functions <br /> The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). <br /> To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum. <br /> Code Sample 3: Compute.java <br /> package jsp2.examples.el; <br /> import java.util.*; <br /> public class Compute { <br /> public static int add(String x, String y) { <br /> int a = 0; <br /> int b = 0; <br /> try { <br /> a = Integer.parseInt(x); <br /> b = Integer.parseInt(y); <br /> } <br /> catch(Exception e) { <br /> } <br /> return a + b; <br /> } <br /> } <br /> Once this is successfully compiled using javac, the next step is to map the function&apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later. <br /> Code Sample 4: Function Descriptor <br /> &lt;function&gt; <br /> &lt;description&gt;add x and y&lt;/description&gt; <br /> &lt;name&gt;add&lt;/name&gt; <br /> &lt;function-class&gt;jsp2.examples.el.Compute &lt;/function-class&gt; <br /> &lt;function-signature&gt;int add(java.lang.String,java.lang.String) &lt;/function-signature&gt; <br /> &lt;/function&gt; <br /> Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &quot;Add Numbers&quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page. <br /> Code Sample 5: math.jsp <br /> &lt;%@ taglib prefix=&quot;my&quot; uri=&quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Functions&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H3&gt;Add Numbers&lt;/H3&gt; <br /> &lt;P&gt; <br /> &lt;FORM action=&quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&quot; method=&quot;GET&quot;&gt; <br /> X = &lt;input type=&quot;text&quot; name=&quot;x&quot; value=&quot;${param[&quot;x&quot;]}&quot;&gt; <br /> &lt;BR&gt; <br /> Y = &lt;input type=&quot;text&quot; name=&quot;y&quot; value=&quot;${param[&quot;y&quot;]}&quot;&gt; <br /> &lt;input type=&quot;submit&quot; value=&quot;Add Numbers&quot;&gt; <br /> &lt;/FORM&gt; <br /> &lt;P&gt; <br /> The sum is: ${my:add(param[&quot;x&quot;],param[&quot;y&quot;])} <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel <br /> Compile Compute.java using javac <br /> Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &lt;/function&gt; in the file and before &lt;/taglib&gt; <br /> Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the jsp file math.jsp from a web browser <br /> If all goes well, you should see something similar to Figure 3. <br /> Figure 3: Using Functions <br />
  • Developing and Using Functions <br /> The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). <br /> To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum. <br /> Code Sample 3: Compute.java <br /> package jsp2.examples.el; <br /> import java.util.*; <br /> public class Compute { <br /> public static int add(String x, String y) { <br /> int a = 0; <br /> int b = 0; <br /> try { <br /> a = Integer.parseInt(x); <br /> b = Integer.parseInt(y); <br /> } <br /> catch(Exception e) { <br /> } <br /> return a + b; <br /> } <br /> } <br /> Once this is successfully compiled using javac, the next step is to map the function&apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later. <br /> Code Sample 4: Function Descriptor <br /> &lt;function&gt; <br /> &lt;description&gt;add x and y&lt;/description&gt; <br /> &lt;name&gt;add&lt;/name&gt; <br /> &lt;function-class&gt;jsp2.examples.el.Compute &lt;/function-class&gt; <br /> &lt;function-signature&gt;int add(java.lang.String,java.lang.String) &lt;/function-signature&gt; <br /> &lt;/function&gt; <br /> Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &quot;Add Numbers&quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page. <br /> Code Sample 5: math.jsp <br /> &lt;%@ taglib prefix=&quot;my&quot; uri=&quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Functions&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H3&gt;Add Numbers&lt;/H3&gt; <br /> &lt;P&gt; <br /> &lt;FORM action=&quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&quot; method=&quot;GET&quot;&gt; <br /> X = &lt;input type=&quot;text&quot; name=&quot;x&quot; value=&quot;${param[&quot;x&quot;]}&quot;&gt; <br /> &lt;BR&gt; <br /> Y = &lt;input type=&quot;text&quot; name=&quot;y&quot; value=&quot;${param[&quot;y&quot;]}&quot;&gt; <br /> &lt;input type=&quot;submit&quot; value=&quot;Add Numbers&quot;&gt; <br /> &lt;/FORM&gt; <br /> &lt;P&gt; <br /> The sum is: ${my:add(param[&quot;x&quot;],param[&quot;y&quot;])} <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel <br /> Compile Compute.java using javac <br /> Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &lt;/function&gt; in the file and before &lt;/taglib&gt; <br /> Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the jsp file math.jsp from a web browser <br /> If all goes well, you should see something similar to Figure 3. <br /> Figure 3: Using Functions <br />
  • Developing and Using Functions <br /> The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). <br /> To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum. <br /> Code Sample 3: Compute.java <br /> package jsp2.examples.el; <br /> import java.util.*; <br /> public class Compute { <br /> public static int add(String x, String y) { <br /> int a = 0; <br /> int b = 0; <br /> try { <br /> a = Integer.parseInt(x); <br /> b = Integer.parseInt(y); <br /> } <br /> catch(Exception e) { <br /> } <br /> return a + b; <br /> } <br /> } <br /> Once this is successfully compiled using javac, the next step is to map the function&apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later. <br /> Code Sample 4: Function Descriptor <br /> &lt;function&gt; <br /> &lt;description&gt;add x and y&lt;/description&gt; <br /> &lt;name&gt;add&lt;/name&gt; <br /> &lt;function-class&gt;jsp2.examples.el.Compute &lt;/function-class&gt; <br /> &lt;function-signature&gt;int add(java.lang.String,java.lang.String) &lt;/function-signature&gt; <br /> &lt;/function&gt; <br /> Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &quot;Add Numbers&quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page. <br /> Code Sample 5: math.jsp <br /> &lt;%@ taglib prefix=&quot;my&quot; uri=&quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Functions&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H3&gt;Add Numbers&lt;/H3&gt; <br /> &lt;P&gt; <br /> &lt;FORM action=&quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&quot; method=&quot;GET&quot;&gt; <br /> X = &lt;input type=&quot;text&quot; name=&quot;x&quot; value=&quot;${param[&quot;x&quot;]}&quot;&gt; <br /> &lt;BR&gt; <br /> Y = &lt;input type=&quot;text&quot; name=&quot;y&quot; value=&quot;${param[&quot;y&quot;]}&quot;&gt; <br /> &lt;input type=&quot;submit&quot; value=&quot;Add Numbers&quot;&gt; <br /> &lt;/FORM&gt; <br /> &lt;P&gt; <br /> The sum is: ${my:add(param[&quot;x&quot;],param[&quot;y&quot;])} <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel <br /> Compile Compute.java using javac <br /> Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &lt;/function&gt; in the file and before &lt;/taglib&gt; <br /> Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the jsp file math.jsp from a web browser <br /> If all goes well, you should see something similar to Figure 3. <br /> Figure 3: Using Functions <br />
  • Tag Handlers <br /> The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: <br /> Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. <br /> Page authors who do not know Java: by using tag files. <br /> Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!. <br /> Code Sample 6: HelloTag.java <br /> package jsp2.examples.simpletag; <br /> import javax.servlet.jsp.JspException; <br /> import javax.servlet.jsp.tagext.SimpleTagSupport; <br /> import java.io.IOException; <br /> /** <br /> * SimpleTag handler that prints &quot;This is my first tag!“ <br /> */ <br /> public class HelloTag extends SimpleTagSupport { <br /> public void doTag() throws JspException, IOException { <br /> getJspContext().getOut().write(&quot;This is my first tag!&quot;); <br /> } <br /> } <br /> Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor: <br /> Code Sample 7: Tag Descriptor <br /> &lt;tag&gt; <br /> &lt;description&gt;Prints this is my first tag&lt;/description&gt; <br /> &lt;name&gt;hello&lt;/name&gt; <br /> &lt;tag-class&gt;jsp2.examples.simpletag.HelloTag&lt;/tag-class&gt; <br /> &lt;body-content&gt;empty&lt;/body-content&gt; <br /> &lt;/tag&gt; <br /> And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed. <br /> &lt;%@ taglib prefix=&quot;mytag&quot; uri=&quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Simple Tag Handler&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Simple Tag Handler&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;My first tag prints&lt;/B&gt;: &lt;mytag:hello/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag <br /> Compile the HelloTag.java using javac <br /> Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &lt;/taglib&gt; <br /> Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request helloworld.jsp from a web browser <br /> If all goes well you should see something similar to Figure 4. <br /> Figure 4: Simple Tag Handler Example <br />
  • Tag Handlers <br /> The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: <br /> Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. <br /> Page authors who do not know Java: by using tag files. <br /> Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!. <br /> Code Sample 6: HelloTag.java <br /> package jsp2.examples.simpletag; <br /> import javax.servlet.jsp.JspException; <br /> import javax.servlet.jsp.tagext.SimpleTagSupport; <br /> import java.io.IOException; <br /> /** <br /> * SimpleTag handler that prints &quot;This is my first tag!“ <br /> */ <br /> public class HelloTag extends SimpleTagSupport { <br /> public void doTag() throws JspException, IOException { <br /> getJspContext().getOut().write(&quot;This is my first tag!&quot;); <br /> } <br /> } <br /> Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor: <br /> Code Sample 7: Tag Descriptor <br /> &lt;tag&gt; <br /> &lt;description&gt;Prints this is my first tag&lt;/description&gt; <br /> &lt;name&gt;hello&lt;/name&gt; <br /> &lt;tag-class&gt;jsp2.examples.simpletag.HelloTag&lt;/tag-class&gt; <br /> &lt;body-content&gt;empty&lt;/body-content&gt; <br /> &lt;/tag&gt; <br /> And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed. <br /> &lt;%@ taglib prefix=&quot;mytag&quot; uri=&quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Simple Tag Handler&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Simple Tag Handler&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;My first tag prints&lt;/B&gt;: &lt;mytag:hello/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag <br /> Compile the HelloTag.java using javac <br /> Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &lt;/taglib&gt; <br /> Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request helloworld.jsp from a web browser <br /> If all goes well you should see something similar to Figure 4. <br /> Figure 4: Simple Tag Handler Example <br />
  • Tag Handlers <br /> The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: <br /> Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. <br /> Page authors who do not know Java: by using tag files. <br /> Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!. <br /> Code Sample 6: HelloTag.java <br /> package jsp2.examples.simpletag; <br /> import javax.servlet.jsp.JspException; <br /> import javax.servlet.jsp.tagext.SimpleTagSupport; <br /> import java.io.IOException; <br /> /** <br /> * SimpleTag handler that prints &quot;This is my first tag!“ <br /> */ <br /> public class HelloTag extends SimpleTagSupport { <br /> public void doTag() throws JspException, IOException { <br /> getJspContext().getOut().write(&quot;This is my first tag!&quot;); <br /> } <br /> } <br /> Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor: <br /> Code Sample 7: Tag Descriptor <br /> &lt;tag&gt; <br /> &lt;description&gt;Prints this is my first tag&lt;/description&gt; <br /> &lt;name&gt;hello&lt;/name&gt; <br /> &lt;tag-class&gt;jsp2.examples.simpletag.HelloTag&lt;/tag-class&gt; <br /> &lt;body-content&gt;empty&lt;/body-content&gt; <br /> &lt;/tag&gt; <br /> And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed. <br /> &lt;%@ taglib prefix=&quot;mytag&quot; uri=&quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Simple Tag Handler&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Simple Tag Handler&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;My first tag prints&lt;/B&gt;: &lt;mytag:hello/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag <br /> Compile the HelloTag.java using javac <br /> Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &lt;/taglib&gt; <br /> Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request helloworld.jsp from a web browser <br /> If all goes well you should see something similar to Figure 4. <br /> Figure 4: Simple Tag Handler Example <br />
  • Tag Handlers <br /> The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: <br /> Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. <br /> Page authors who do not know Java: by using tag files. <br /> Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!. <br /> Code Sample 6: HelloTag.java <br /> package jsp2.examples.simpletag; <br /> import javax.servlet.jsp.JspException; <br /> import javax.servlet.jsp.tagext.SimpleTagSupport; <br /> import java.io.IOException; <br /> /** <br /> * SimpleTag handler that prints &quot;This is my first tag!“ <br /> */ <br /> public class HelloTag extends SimpleTagSupport { <br /> public void doTag() throws JspException, IOException { <br /> getJspContext().getOut().write(&quot;This is my first tag!&quot;); <br /> } <br /> } <br /> Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor: <br /> Code Sample 7: Tag Descriptor <br /> &lt;tag&gt; <br /> &lt;description&gt;Prints this is my first tag&lt;/description&gt; <br /> &lt;name&gt;hello&lt;/name&gt; <br /> &lt;tag-class&gt;jsp2.examples.simpletag.HelloTag&lt;/tag-class&gt; <br /> &lt;body-content&gt;empty&lt;/body-content&gt; <br /> &lt;/tag&gt; <br /> And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed. <br /> &lt;%@ taglib prefix=&quot;mytag&quot; uri=&quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Simple Tag Handler&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Simple Tag Handler&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;My first tag prints&lt;/B&gt;: &lt;mytag:hello/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag <br /> Compile the HelloTag.java using javac <br /> Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &lt;/taglib&gt; <br /> Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request helloworld.jsp from a web browser <br /> If all goes well you should see something similar to Figure 4. <br /> Figure 4: Simple Tag Handler Example <br />
  • Tag Handlers <br /> The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: <br /> Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. <br /> Page authors who do not know Java: by using tag files. <br /> Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!. <br /> Code Sample 6: HelloTag.java <br /> package jsp2.examples.simpletag; <br /> import javax.servlet.jsp.JspException; <br /> import javax.servlet.jsp.tagext.SimpleTagSupport; <br /> import java.io.IOException; <br /> /** <br /> * SimpleTag handler that prints &quot;This is my first tag!“ <br /> */ <br /> public class HelloTag extends SimpleTagSupport { <br /> public void doTag() throws JspException, IOException { <br /> getJspContext().getOut().write(&quot;This is my first tag!&quot;); <br /> } <br /> } <br /> Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor: <br /> Code Sample 7: Tag Descriptor <br /> &lt;tag&gt; <br /> &lt;description&gt;Prints this is my first tag&lt;/description&gt; <br /> &lt;name&gt;hello&lt;/name&gt; <br /> &lt;tag-class&gt;jsp2.examples.simpletag.HelloTag&lt;/tag-class&gt; <br /> &lt;body-content&gt;empty&lt;/body-content&gt; <br /> &lt;/tag&gt; <br /> And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed. <br /> &lt;%@ taglib prefix=&quot;mytag&quot; uri=&quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Simple Tag Handler&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Simple Tag Handler&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;My first tag prints&lt;/B&gt;: &lt;mytag:hello/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag <br /> Compile the HelloTag.java using javac <br /> Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &lt;/taglib&gt; <br /> Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request helloworld.jsp from a web browser <br /> If all goes well you should see something similar to Figure 4. <br /> Figure 4: Simple Tag Handler Example <br />
  • Tag File <br /> The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag. <br /> To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file! <br /> Code Sample 9: greetings.tag <br /> Hello there. How are you doing? <br /> Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10. <br /> Code Sample 10: chat.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;JSP 2.0 Examples - Hello World Using a Tag File&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Tag File Example&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;The output of my first tag file is&lt;/B&gt;: &lt;tags:greetings/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags <br /> Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the chat.jsp file from a Web browser <br /> If all goes well, you should see something similar to Figure 5. <br /> Figure 5: Simple Tag File Example <br /> Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it! <br /> Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; &lt;%@ attribute name=&quot;title&quot; %&gt; &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; &lt;TR&gt; &lt;TD&gt;&lt;B&gt;${title}&lt;/B&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; &lt;jsp:doBody/&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; &lt;TABLE border=&quot;0&quot;&gt; &lt;TR valign=&quot;top&quot;&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; Last French Concorde Arrives in NY&lt;br/&gt; Another Travel Headline&lt;br/&gt; Yet Another Travel Headline&lt;br/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; Java for in-flight entertainment&lt;BR&gt; Another Technology Headline&lt;BR&gt; Another Technology Headline&lt;BR&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; American Football&lt;BR/&gt; NBA&lt;BR/&gt; Soccer&lt;BR/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • Tag File <br /> The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag. <br /> To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file! <br /> Code Sample 9: greetings.tag <br /> Hello there. How are you doing? <br /> Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10. <br /> Code Sample 10: chat.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;JSP 2.0 Examples - Hello World Using a Tag File&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Tag File Example&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;The output of my first tag file is&lt;/B&gt;: &lt;tags:greetings/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags <br /> Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the chat.jsp file from a Web browser <br /> If all goes well, you should see something similar to Figure 5. <br /> Figure 5: Simple Tag File Example <br /> Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it! <br /> Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; &lt;%@ attribute name=&quot;title&quot; %&gt; &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; &lt;TR&gt; &lt;TD&gt;&lt;B&gt;${title}&lt;/B&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; &lt;jsp:doBody/&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; &lt;TABLE border=&quot;0&quot;&gt; &lt;TR valign=&quot;top&quot;&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; Last French Concorde Arrives in NY&lt;br/&gt; Another Travel Headline&lt;br/&gt; Yet Another Travel Headline&lt;br/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; Java for in-flight entertainment&lt;BR&gt; Another Technology Headline&lt;BR&gt; Another Technology Headline&lt;BR&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; American Football&lt;BR/&gt; NBA&lt;BR/&gt; Soccer&lt;BR/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • Tag File <br /> The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag. <br /> To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file! <br /> Code Sample 9: greetings.tag <br /> Hello there. How are you doing? <br /> Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10. <br /> Code Sample 10: chat.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;JSP 2.0 Examples - Hello World Using a Tag File&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;Tag File Example&lt;/H2&gt; <br /> &lt;P&gt; <br /> &lt;B&gt;The output of my first tag file is&lt;/B&gt;: &lt;tags:greetings/&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags <br /> Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the chat.jsp file from a Web browser <br /> If all goes well, you should see something similar to Figure 5. <br /> Figure 5: Simple Tag File Example <br /> Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it! <br /> Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; &lt;%@ attribute name=&quot;title&quot; %&gt; &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; &lt;TR&gt; &lt;TD&gt;&lt;B&gt;${title}&lt;/B&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; &lt;jsp:doBody/&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; &lt;TABLE border=&quot;0&quot;&gt; &lt;TR valign=&quot;top&quot;&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; Last French Concorde Arrives in NY&lt;br/&gt; Another Travel Headline&lt;br/&gt; Yet Another Travel Headline&lt;br/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; Java for in-flight entertainment&lt;BR&gt; Another Technology Headline&lt;BR&gt; Another Technology Headline&lt;BR&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; American Football&lt;BR/&gt; NBA&lt;BR/&gt; Soccer&lt;BR/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; &lt;%@ attribute name=&quot;title&quot; %&gt; &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; &lt;TR&gt; &lt;TD&gt;&lt;B&gt;${title}&lt;/B&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; &lt;jsp:doBody/&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; &lt;TABLE border=&quot;0&quot;&gt; &lt;TR valign=&quot;top&quot;&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; Last French Concorde Arrives in NY&lt;br/&gt; Another Travel Headline&lt;br/&gt; Yet Another Travel Headline&lt;br/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; Java for in-flight entertainment&lt;BR&gt; Another Technology Headline&lt;BR&gt; Another Technology Headline&lt;BR&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;TD&gt; &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; American Football&lt;BR/&gt; NBA&lt;BR/&gt; Soccer&lt;BR/&gt; &lt;/tags:display&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; <br /> &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; <br /> &lt;%@ attribute name=&quot;title&quot; %&gt; <br /> &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; <br /> &lt;TR&gt; <br /> &lt;TD&gt; <br /> &lt;B&gt;${title}&lt;/B&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;TR&gt; <br /> &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; <br /> &lt;jsp:doBody/&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; <br /> &lt;TABLE border=&quot;0&quot;&gt; <br /> &lt;TR valign=&quot;top&quot;&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; <br /> Last French Concorde Arrives in NY&lt;br/&gt; <br /> Another Travel Headline&lt;br/&gt; <br /> Yet Another Travel Headline&lt;br/&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; <br /> Java for in-flight entertainment&lt;BR&gt; <br /> Another Technology Headline&lt;BR&gt; <br /> Another Technology Headline&lt;BR&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; <br /> American Football&lt;BR/&gt; <br /> NBA&lt;BR/&gt; <br /> Soccer&lt;BR/&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;/TABLE&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • Another Tag File Example <br /> Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &lt;attribute&gt; element in the TLD; it allows for the declaration of custom action attributes. <br /> Code Sample 11: display.tag <br /> &lt;%@ attribute name=&quot;color&quot; %&gt; <br /> &lt;%@ attribute name=&quot;bgcolor&quot; %&gt; <br /> &lt;%@ attribute name=&quot;title&quot; %&gt; <br /> &lt;TABLE border=&quot;0&quot; bgcolor=&quot;${color}&quot;&gt; <br /> &lt;TR&gt; <br /> &lt;TD&gt; <br /> &lt;B&gt;${title}&lt;/B&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;TR&gt; <br /> &lt;TD bgcolor=&quot;${bgcolor}&quot;&gt; <br /> &lt;jsp:doBody/&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;/TABLE&gt; <br /> Code Sample 12 shows a simple JSP page that uses the display tag. <br /> Code Sample 12: newsportal.jsp <br /> &lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags&quot; %&gt; <br /> &lt;HTML&gt; <br /> &lt;HEAD&gt; <br /> &lt;TITLE&gt;Another Tag File Example&lt;/TITLE&gt; <br /> &lt;/HEAD&gt; <br /> &lt;BODY&gt; <br /> &lt;H2&gt;News Portal: Another Tag File Example&lt;/H2&gt; <br /> &lt;TABLE border=&quot;0&quot;&gt; <br /> &lt;TR valign=&quot;top&quot;&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#ff0000&quot; bgcolor=&quot;#ffc0c0&quot; title=&quot;Travel&quot;&gt; <br /> Last French Concorde Arrives in NY&lt;br/&gt; <br /> Another Travel Headline&lt;br/&gt; <br /> Yet Another Travel Headline&lt;br/&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#00fc00&quot; bgcolor=&quot;#c0ffc0&quot; title=&quot;Technology&quot;&gt; <br /> Java for in-flight entertainment&lt;BR&gt; <br /> Another Technology Headline&lt;BR&gt; <br /> Another Technology Headline&lt;BR&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;TD&gt; <br /> &lt;tags:display color=&quot;#ffcc11&quot; bgcolor=&quot;#ffffcc&quot; title=&quot;Sports&quot;&gt; <br /> American Football&lt;BR/&gt; <br /> NBA&lt;BR/&gt; <br /> Soccer&lt;BR/&gt; <br /> &lt;/tags:display&gt; <br /> &lt;/TD&gt; <br /> &lt;/TR&gt; <br /> &lt;/TABLE&gt; <br /> &lt;/BODY&gt; <br /> &lt;/HTML&gt; <br /> To run this example: <br /> Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag <br /> Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial <br /> Request the newsportal.jsp from a Web browser <br /> Now, you should see something similar to Figure 6. <br /> Figure 6: Using Tag File as a Template <br />
  • 8.1 Overview <br /> There are three key concepts associated with internationalization: locale, resource <br /> bundle, and basename. <br /> A locale represents a specific geographical, political, or cultural region. A locale is <br /> identified by a language code, along with an optional country code1. <br /> 1. Language code <br /> The language code is the lower-case two-letter code as defined by ISO-639 (e.g. <br /> “ca” for Catalan, “zh” for Chinese). The full list of these codes can be found at a <br /> number of sites, such as: <br /> http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt <br /> 2. Country code <br /> The country code is the upper-case two-letter code as defined by ISO-3166 (e.g. <br /> “IT” for Italy, “CR” for Costa Rica). The full list of these codes can be found at a <br /> number of sites, such as: <br /> http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html. <br /> A resource bundle contains locale-specific objects. Each message in a resource bundle <br /> is associated with a key. Since the set of messages contained in a resource bundle can <br /> be localized for many locales, the resource bundles that translate the same set of <br /> messages are identified by the same basename. A specific resource bundle is therefore <br /> uniquely identified by combining its basename with a locale. <br /> For instance, a web application could define the registration resource bundles with <br /> basename Registration to contain the messages associated with the registration <br /> portion of the application. Assuming that French and English are the only languages <br /> supported by the application, there will be two resource bundles: <br /> Registration_fr (French language) and Registration_en (English language). <br /> Depending on the locale associated with the client request, the key “greeting” could <br /> be mapped to the message “Bonjour” (French) or “Hello” (English). <br />
  • 8.1 Overview <br /> There are three key concepts associated with internationalization: locale, resource <br /> bundle, and basename. <br /> A locale represents a specific geographical, political, or cultural region. A locale is <br /> identified by a language code, along with an optional country code1. <br /> 1. Language code <br /> The language code is the lower-case two-letter code as defined by ISO-639 (e.g. <br /> “ca” for Catalan, “zh” for Chinese). The full list of these codes can be found at a <br /> number of sites, such as: <br /> http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt <br /> 2. Country code <br /> The country code is the upper-case two-letter code as defined by ISO-3166 (e.g. <br /> “IT” for Italy, “CR” for Costa Rica). The full list of these codes can be found at a <br /> number of sites, such as: <br /> http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html. <br /> A resource bundle contains locale-specific objects. Each message in a resource bundle <br /> is associated with a key. Since the set of messages contained in a resource bundle can <br /> be localized for many locales, the resource bundles that translate the same set of <br /> messages are identified by the same basename. A specific resource bundle is therefore <br /> uniquely identified by combining its basename with a locale. <br /> For instance, a web application could define the registration resource bundles with <br /> basename Registration to contain the messages associated with the registration <br /> portion of the application. Assuming that French and English are the only languages <br /> supported by the application, there will be two resource bundles: <br /> Registration_fr (French language) and Registration_en (English language). <br /> Depending on the locale associated with the client request, the key “greeting” could <br /> be mapped to the message “Bonjour” (French) or “Hello” (English). <br />
  • 8.1.1 &lt;fmt:message&gt; <br /> It is possible to internationalize the JSP pages of a web application simply by using <br /> the &lt;fmt:message&gt; action as shown below: <br /> &lt;fmt:message key=&quot;greeting&quot;/&gt; <br /> In this case, &lt;fmt:message&gt; leverages the default i18n localization context, making it <br /> extremely simple for a page author to internationalize JSP pages. <br /> &lt;fmt:message&gt; also supports compound messages, i.e. messages that contain one or <br /> more variables. Parameter values for these variables may be supplied via one or <br /> more &lt;fmt:param&gt; subtags (one for each parameter value). This procedure is <br /> referred to as parametric replacement. <br /> &lt;fmt:message key=&quot;athletesRegistered&quot;&gt; <br /> &lt;fmt:param&gt; <br /> &lt;fmt:formatNumber value=”${athletesCount}”/&gt; <br /> &lt;/fmt:param&gt; <br /> &lt;/fmt:message&gt; <br /> Depending on the locale, this example could print the following messages: <br /> french: Il y a 10 582 athletes enregistres. <br /> english: There are 10,582 athletes registered. <br />
  • 8.1.1 &lt;fmt:message&gt; <br /> It is possible to internationalize the JSP pages of a web application simply by using <br /> the &lt;fmt:message&gt; action as shown below: <br /> &lt;fmt:message key=&quot;greeting&quot;/&gt; <br /> In this case, &lt;fmt:message&gt; leverages the default i18n localization context, making it <br /> extremely simple for a page author to internationalize JSP pages. <br /> &lt;fmt:message&gt; also supports compound messages, i.e. messages that contain one or <br /> more variables. Parameter values for these variables may be supplied via one or <br /> more &lt;fmt:param&gt; subtags (one for each parameter value). This procedure is <br /> referred to as parametric replacement. <br /> &lt;fmt:message key=&quot;athletesRegistered&quot;&gt; <br /> &lt;fmt:param&gt; <br /> &lt;fmt:formatNumber value=”${athletesCount}”/&gt; <br /> &lt;/fmt:param&gt; <br /> &lt;/fmt:message&gt; <br /> Depending on the locale, this example could print the following messages: <br /> french: Il y a 10 582 athletes enregistres. <br /> english: There are 10,582 athletes registered. <br />
  • 8.2I18n Localization Context <br /> I18n actions use an i18n localization context to localize their data. An i18n <br /> localization context contains two pieces of information: a resource bundle and the <br /> locale for which the resource bundle was found. <br /> An i18n action determine its i18n localization context in one of several ways, which <br /> are described in order of precedence: <br /> &lt;fmt:message&gt; bundle attribute <br /> If attribute bundle is specified in &lt;fmt:message&gt;, the i18n localization context associated with it is used for localization. <br /> &lt;fmt:bundle&gt; action <br /> If &lt;fmt:message&gt; actions are nested inside a &lt;fmt:bundle&gt; action, the i18n localization context of the enclosing &lt;fmt:bundle&gt; action is used for localization. The &lt;fmt:bundle&gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename. <br /> I18n default localization context <br /> The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename. <br /> The example below shows how the various localization contexts can be established <br /> to define the resource bundle used for localization. <br /> &lt;%-- Use configuration setting --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;fmt:setBundle basename=&quot;Errors&quot; var=&quot;errorBundle&quot; /&gt; <br /> &lt;fmt:bundle basename=&quot;Greetings&quot;&gt; <br /> &lt;%-- Localization context established by <br /> parent &lt;fmt:bundle&gt; tag --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;%-- Localization context established by attribute bundle --%&gt; <br /> &lt;fmt:message key=&quot;WrongPassword&quot; bundle=&quot;${errorBundle}&quot; /&gt; <br /> &lt;/fmt:bundle&gt; <br /> I18n actions use an i18n localization context to localize their data. An i18n <br /> localization context contains two pieces of information: a resource bundle and the <br /> locale for which the resource bundle was found. <br /> An i18n action determine its i18n localization context in one of several ways, which <br /> are described in order of precedence: <br /> &lt;fmt:message&gt; bundle attribute <br /> If attribute bundle is specified in &lt;fmt:message&gt;, the i18n localization context associated with it is used for localization. <br /> &lt;fmt:bundle&gt; action <br /> If &lt;fmt:message&gt; actions are nested inside a &lt;fmt:bundle&gt; action, the i18n localization context of the enclosing &lt;fmt:bundle&gt; action is used for localization. The &lt;fmt:bundle&gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename. <br /> I18n default localization context <br /> The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename. <br /> The example below shows how the various localization contexts can be established <br /> to define the resource bundle used for localization. <br /> &lt;%-- Use configuration setting --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;fmt:setBundle basename=&quot;Errors&quot; var=&quot;errorBundle&quot; /&gt; <br /> &lt;fmt:bundle basename=&quot;Greetings&quot;&gt; <br /> &lt;%-- Localization context established by <br /> parent &lt;fmt:bundle&gt; tag --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;%-- Localization context established by attribute bundle --%&gt; <br /> &lt;fmt:message key=&quot;WrongPassword&quot; bundle=&quot;${errorBundle}&quot; /&gt; <br /> &lt;/fmt:bundle&gt; <br />
  • 8.2I18n Localization Context <br /> I18n actions use an i18n localization context to localize their data. An i18n <br /> localization context contains two pieces of information: a resource bundle and the <br /> locale for which the resource bundle was found. <br /> An i18n action determine its i18n localization context in one of several ways, which <br /> are described in order of precedence: <br /> &lt;fmt:message&gt; bundle attribute <br /> If attribute bundle is specified in &lt;fmt:message&gt;, the i18n localization context associated with it is used for localization. <br /> &lt;fmt:bundle&gt; action <br /> If &lt;fmt:message&gt; actions are nested inside a &lt;fmt:bundle&gt; action, the i18n localization context of the enclosing &lt;fmt:bundle&gt; action is used for localization. The &lt;fmt:bundle&gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename. <br /> I18n default localization context <br /> The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename. <br /> The example below shows how the various localization contexts can be established <br /> to define the resource bundle used for localization. <br /> &lt;%-- Use configuration setting --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;fmt:setBundle basename=&quot;Errors&quot; var=&quot;errorBundle&quot; /&gt; <br /> &lt;fmt:bundle basename=&quot;Greetings&quot;&gt; <br /> &lt;%-- Localization context established by parent &lt;fmt:bundle&gt; tag --%&gt; <br /> &lt;fmt:message key=&quot;Welcome&quot; /&gt; <br /> &lt;%-- Localization context established by attribute bundle --%&gt; <br /> &lt;fmt:message key=&quot;WrongPassword&quot; bundle=&quot;${errorBundle}&quot; /&gt; <br /> &lt;/fmt:bundle&gt; <br />
  • Preferred Locales <br /> If the resource bundle of an i18n localization context needs to be determined, it is <br /> retrieved from the web application’s resources according to the algorithm described <br /> in section Section 8.3. This algorithm requires two pieces of information: the <br /> basename of the resource bundle (as described in the previous section) and the <br /> preferred locales. <br /> The method for setting the preferred locales is characterized as either applicationbased <br /> or browser-based. <br /> Application-based locale setting has priority over browser-based locale setting. In this <br /> mode, the locale is set via the javax.servlet.jsp.jstl.fmt.locale <br /> configuration setting (see Section 8.11.1). Setting the locale this way is useful in <br /> situations where an application lets its users pick their preferred locale and then sets <br /> the scoped variable accordingly. This may also be useful in the case where a client’s <br /> preferred locale is retrieved from a database and installed for the page using the <br /> &lt;fmt:setLocale&gt; action. <br />
  • Offers simpler consistent programming environment. <br /> Advanced programmers may prefer scriptlets over JSTL. <br /> JSTL allows HTML programmers to program in one consistent environment. <br /> Back-end programmers still create JavaBeans, which are used in conjunction with JSTL. <br /> Conclusion <br /> JSP 2.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages. Despite the fact the word &quot;Java&quot; appears in JavaServer Pages, with JSP 2.0 page authors can develop innovative dynamic Web pages without having to learn the Java programming language. The examples shown throughout the article demonstrate how easy it is to get started using the new features in JSP 2.0 to develop dynamic Web pages. <br />

Jstl Guide Jstl Guide Presentation Transcript

  • Introduction To JSTL (Java Server Pages Tag Library) Author: Yuval Zilberstein, yuvalzi@gmail.com
  • Advantages • Avoid conflicts between jar versions (XML, JDBC etc’) • Eases page development for page authors • Easy to read and maintain • Reuse of valuable components • As a matter of principle – A JSP page should be a view page without scriptlets.
  • Disadvantages • Not as flexible as scriptlets • May seem burdensome for experienced programmers • Not a general purpose programming language. • Hard to debug
  • Installing • The following must be available in your project – standard.jar – jstl.jar – web.xml – DOCTYPE – Some containers must have a DOCTYPE element in web.xml
  • Installing • web.xml example <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>Learning JSTL (or whatever you like</description> </web-app>
  • EL Expression Language • A data access language, that eases access to application data. • Allows page authors to access an object using a simplified syntax: – <someTags:aTag attribute="${aName}"> – <someTags.aTag attribute="${aCustomer.address.country}">
  • Accessing Application Data • EL expressions must be enclosed between ${ and }. • ${data} – scoped variable data. • The dot (.) operator. • The bracket ['name'] operator. • E.g. – ${customer.name} – ${customer["name"]} – ${customers[0]} • ${customer.name} is equivalent to $ {customer["name"]}.
  • Operators • The second version (in parenthesis) is to avoid the use of entity references in XML syntax Operator Description + Addition - Subtraction * Multiplication / ( or div) Division % ( or mod ) Modulus (Reminder) == ( or eq ) Equality != ( or ne ) Inequity < ( or lt ) Less than > ( or gt ) Greater than <= ( or le ) Less than or equal >= ( or ge ) Greater than or equal && ( or and ) Logical AND || ( or or ) Logical OR ! ( or not ) Boolean complement empty Check for empty value
  • Implicit Objects Implicit Object Content pageScope access to the scoped variables requestScope access to the scoped variables sessionScope access to the scoped variables applicationScope access to the scoped variables param a Map object. param["foo"] returns the first string value associated with request parameter foo. paramValues a Map object. paramValues["foo"] returns an array of strings associated with request parameter foo. header a Map object. header["foo"] returns the first string value associated with header foo. headerValues a Map object. headerValues["foo"] returns an array of strings associated with header foo. initParam access to context initialization parameters cookie exposes cookies received in the request pageContext PageContext properties (e.g. HttpServletRequest, ServletContext, HttpSession)
  • Tag libraries • There are two groups of twin tag libraries – one that supports the expression language (EL) – one that supports request time expression values (RT) (using scriptlets) EL-based Tag Libraries Functional Area URI Prefix core http://java.sun.com/jstl/core c XML processing http://java.sun.com/jstl/xml x I18N capable formatting http://java.sun.com/jstl/fmt fmt relational db access (SQL) http://java.sun.com/jstl/sql sql RT-based Tag Libraries Functional Area URI Prefix core http://java.sun.com/jstl/core_rt c_rt XML processing http://java.sun.com/jstl/xml_rt x_rt I18N capable formatting http://java.sun.com/jstl/fmt_rt fmt_rt relational db access (SQL) http://java.sun.com/jstl/sql_rt sql_rt
  • Tag libraries • To use a JSTL library, you declare it: – E.g.: <@ taglib prefix="c" uri="http://java.sun.com/jstl/core"> • prefix attribute – Namespace reference
  • The Core Tag Library http://java.sun.com/jstl/core
  • The Core Tag Library • Supports the following abilities – Output – Manipulation of scoped variables – Conditional logic – Loops – URL manipulation – Error handling.
  • General Purpose Tags • <c:out> - writing data • <c:set> - set the value of a scoped attribute • <c:remove> - remove a scoped variable. • <c:catch> - handling errors
  • General Purpose Tags • Print with a default value: – <c:out value="${customer.city}" default="unknown"/> • Setting a variable – <c:set var="name" value="expression"/> • Setting with an inline body – <c:set var="xmltext"> <books> <book> <title>Book Title A</title> <author>A. B. C.</author> <price>17.95</price> </book> </books> </c:set> • Setting with an inline body – <c:remove var="cache" scope="application/>
  • Conditional Actions • <c:if> • If / then / else – Consists of the following three tags: – <c:choose> – <c:when> – <c:otherwise> • Conditional actions use the attribute test to check weather the condition has a true or false value
  • Conditional Actions – E.g. • <c:if> example: – <c:if test="${customer.country == 'Canada'}"> This customer is based in Canada. </c:if> • <c:if> and <c:catch> • <c:catch var="exception"> <!-- execution we can recover from. --> ... </c:catch> <c:if test="${exception != null}"> Processing could not be performed. Here is why.... </c:if>
  • Conditional Actions – E.g. • <c:choose> <c:when test="${customer.country == 'UK'}"> UK has mild winters. </c:when> <c:otherwise> Country is unknown. </c:otherwise> </c:choose>
  • Iteration Actions - forEach • <c:forEach> iteration over collection of items. • <c:forEach var="customer" items="${customers}"> Customer: <c:out value="${customer}"/> </c:forEach> • <c:forEach var=“i" begin="1" end="100"> <c:out value="${i % 2 == 0}"/> </c:forEach>
  • Iteration Actions - forEach • E.g.: Print the headers • <c:forEach var="head" items="${headerValues}"> param: <c:out value="${head.key}"/><br> values: <c:forEach var="val" items="${head.value}"> <c:out value="${val}"/> </c:forEach> <p> </c:forEach> </body> </html>
  • URL Actions • <c:import> - import local and remote resources. • As opposed to the standard jsp include action and directive, the jstl import allows importing of remote resources. – <c:import url="./copyright.html"/> – <c:import url="http://www.somewhere.com/hello.xml"/>
  • URL Actions • <c:url> - URL rewriting tasks. • It can be combined with <c:param>, which encodes query-string parameters. • <c:url value="http://www.somewhere.com/customers/register" var="registrationURL"> <c:param name="name" value="${param.name}"/> <c:param name="country" value="${param.country}"/> </c:url> <a href='<c:out value="${registrationURL}"/>'>Customer Registration>/a>
  • URL Actions • <c:redirect> (to support HTTP redirect) • <c:redirect url="https://www.somewhere.com/register">
  • The XML Tag Library http://java.sun.com/jstl/xml
  • The XML Tag Library • XML actions to address basic needs of page authors. • Support XPath expressions - Path expressions to identify nodes in XML.
  • XML Core actions • <x:out> - writing XML data • <x:set> - set the value of an XML attribute • <x:parse> - parse the document
  • XML Control Flow • <x:if> • If .. Then .. else – <x:choose> – <x:when> – <x:otherwise> • <x:forEach> • Xml control flow tags use the select attribute to match to an XPath expressions.
  • XML control flow • <x:parse xml="${xmldoc}" var="output"/> ---------------------------------------------------- • <x:if select="$output/portfolio/stock[symbol = 'SUNW']"> You still have Microsystems Stocks! </x:if> ---------------------------------------------------- • <x:forEach select="$output/portfolio/stock"> <x:out select="price"/> </x:forEach>
  • XML control flow <x:choose> <x:when select="$output/portfolio/stock[price > '70']"> You still have stocks worth over $70. </x:when> <x:otherwise> You have no stocks worth over $70. </x:otherwise> </x:choose>
  • Code Sample 1 <c:set var="xmltext"> <books> <book> <title>Book Title A</title> <author>A. B. C.</author> <price>17.95</price> </book> <book> <title>Book Title B</title> <author>X. Y. Z.</author> <price>24.99</price> </book> </books> </c:set> <x:parse xml="${xmltext}" var="output"/> The title of the first book is: <x:out select="$output/books/book[1]/title"/> The price of the second book: <x:out select="$output/books/book[2]/price"/>
  • Code Sample 2 http://www.javacourses.com/stocks .xml<?xml version="1.0" encoding="UTF-8"?> <portfolio> <stock> <symbol>SUNW</symbol> <name>Sun Microsystems</name> <price>17.1</price> </stock> <stock> <symbol>AOL</symbol> <name>America Online</name> <price>51.05</price> </stock> <stock> <symbol>IBM</symbol> <name>International Business Machines</name> <price>116.10</price> </stock> <stock> <symbol>MOT</symbol> <name>Motorola</name> <price>15.20</price> </stock> </portfolio>
  • Code Sample 2 • Import the document from remote web server : – <c:import url="http://www.javacourses.com/stocks.xml" var="xmldoc"/>
  • Code Sample 3: xml-ex2.jsp <c:import url="http://www.javacourses.com/stocks.xml" var="xmldoc"/> <x:parse xml="${xmldoc}" var="output"/> <x:forEach select="$output/portfolio/stock" var="item"> <x:out select="symbol"/> <x:out select="name"/> <x:out select="price"/> </x:forEach>
  • Transforming XML • Supports XSLT to transform XML within JSP pages • The result of the transformation is written to the page.
  • Code Sample 5: xml-ex3.jsp <h3>Transforming stocks.xml into HTML using stocks.xsl</h3> <c:import url="http://www.javacourses.com/stocks.xml" var="xmldocument"/> <c:import url="./stocks.xsl" var="xslt"/> <x:transform xml="${xmldocument}" xslt="${xslt}"/>
  • The SQL Tag Library http://java.sun.com/jstl/sql
  • The SQL Tag Library • For special and unique situations • E.g.: – prototyping/testing – small scale/simple applications – lack of developer resources • Provide basic capabilities to interact with databases.
  • The SQL Tag Library • Perform database queries (select) • Easily access query results • Perform database updates (insert, update, delete) • Run transactions
  • Data Source • SQL actions operate on a data source • Is specified by: – dataSource attribute in SQL actions – configuration setting: javax.servlet.jsp.jstl.sql.dataSou rce. – data source action: • JNDI relative path. • JDBC Parameters
  • Querying a Database • <sql:query>
  • Querying a Database <sql:query var="customers" dataSource="${dataSource}"> SELECT * FROM customers WHERE country = ’China’ ORDER BY lastname </sql:query> ---------------------------------------------------------- <c:forEach var="row" items="${customers.rows}"> <c:out value="${row.lastName}"/> <c:out value="${row.firstName}"/> <c:out value="${row.address}"/> </c:forEach>
  • Querying a Database <!-- column headers --> <c:forEach var=”columnName” items=”${result.columnNames}”> <c:out value="${columnName}"/> </c:forEach> ---------------------------------------------------------- <!-- column data --> <c:forEach var="row" items="${result.rowsByIndex}"> <c:forEach var="column" items="${row}"> <td><c:out value="${column}"/></td> </c:forEach> </c:forEach>
  • Updating a Database • <sql:update>
  • Updating a Database <sql:transaction dataSource="${dataSource}"> <sql:update> UPDATE account SET Balance = Balance - ? WHERE accountNo = ? <sql:param value="${transferAmount}"/> <sql:param value="${accountFrom}"/> </sql:update> <sql:update> UPDATE account SET Balance = Balance + ? WHERE accountNo = ? <sql:param value="${transferAmount}"/> <sql:param value="${accountTo}"/> </sql:update> </sql:transaction>
  • SQL Statement Parameters • Implemented by – <sql:query> – <sql:update>
  • SQL Statement Parameters <sql:update> UPDATE PersonalInfo SET BirthDate = ? WHERE clientId = ? <acme:dateParam year="${year}" month="${month}" day="${day}"/> <sql:param value=”${clientId}”/> </sql:update> ----------------------------------------------------------------- <sql:update sql="${sqlUpdateStmt}” dataSource="${dataSource}"> <fmt:parseDate var="myDate" value="${someDate}”/> <sql:param value="${myDate}"/> </sql:update>
  • Database Access • Implemented actions: – <sql:query> – <sql:update> – <sql:transaction> • DataSource attribute of the SQL action. • DataSource name at the “javax.servlet.jsp.jstl.sql.dataSource” configuration setting: – DataSource object – String • Retrieve the data source from the JNDI relative path • JDBC parameters
  • Database Access • <sql:query> • <sql:update> • <sql:transaction> • <sql:setDataSource> • <sql:param> • <sql:dateParam>
  • Configuration Settings
  • Developing and Using Functions
  • Developing and Using Functions • Define expression functions. • Must be programmed as – public static method – public class. • Map signature in a (TLD). – Write the Java code – Map function's signature in the tag library – Write the JSP page that uses the function
  • Developing and Using Functions package jsp2.examples.el; import java.util.*; public class Compute { public static int add(String x, String y) { int a = 0; int b = 0; try { a = Integer.parseInt(x); b = Integer.parseInt(y); } catch(Exception e) { } return a + b; } }
  • Developing and Using Functions <function> <description>add x and y</description> <name>add</name> <function-class>jsp2.examples.el.Compute </function-class> <function-signature> int add(java.lang.String,java.lang.String) </function-signature> </function>
  • Developing and Using Functions <%@ taglib prefix="my" uri="http://jakarta.apache.org/tomcat/jsp2-example- taglib %> <BODY> <H3>Add Numbers</H3> <P> <FORM action="/developer/technicalArticles/javaserverpages/JSP20/math.jsp" method="GET"> X = <input type="text" name="x" value="${param["x"]}"> <BR> Y = <input type="text" name="y" value="${param["y"]}"> <input type="submit" value="Add Numbers"> </FORM> <P> The sum is: ${my:add(param["x"],param["y"])} </BODY> </HTML>
  • Tag Handlers
  • Tag Handlers • Simple Tag Extension (JSP2.0/JSTL1.2) – Java developers: implement javax.servlet.jsp.tagext.SimpleTag interface. – Page authors: tag files.
  • Implementing SimpleTag • Implement javax.servlet.jsp.tagext.Simpl eTag interface. • Define a tag descriptor in a TLD • JSP page that uses the tag
  • Implementing SimpleTag package jsp2.examples.simpletag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; /** * SimpleTag handler that prints "This is my first tag!“ */ public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("This is my first tag!"); } }
  • Implementing SimpleTag <tag> <description>Prints this is my first tag</description> <name>hello</name> <tag-class>jsp2.examples.simpletag.HelloTag</tag-class> <body-content>empty</body-content> </tag>
  • Implementing SimpleTag <%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %> <HTML> <HEAD> <TITLE>Simple Tag Handler</TITLE> </HEAD> <BODY> <H2>Simple Tag Handler</H2> <P> <B>My first tag prints</B>: <mytag:hello/> </BODY> </HTML>
  • Tag File
  • Tag File • Make JSP code reusable • Allow to create reusable tag libraries • .tag extesion
  • Tag File Hello there. How are you doing?
  • Tag File <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <HTML> <HEAD> <TITLE>JSP 2.0 Examples - Hello World Using a Tag File</TITLE> </HEAD> <BODY> <H2>Tag File Example</H2> <P> <B>The output of my first tag file is</B>: <tags:greetings/> </BODY> </HTML>
  • Tag File Templates • Can be used as a template.
  • Tag File Templates • E.g. display.tag: <%@ attribute name="color" %> <%@ attribute name="bgcolor" %> <%@ attribute name="title" %> <TABLE border="0" bgcolor="${color}"> <TR> <TD> <B>${title}</B> </TD> </TR> <TR> <TD bgcolor="${bgcolor}"> <jsp:doBody/> </TD> </TR> </TABLE>
  • Tag File Templates • E.g. newsportal.jsp <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <TABLE border="0"> <TR><TD> <tags:display color="#ff0000" bgcolor="#ffc0c0" title="Travel"> Last French Concorde Arrives in NY<br/> </tags:display> </TD><TD> <tags:display color="#00fc00" bgcolor="#c0ffc0" title="Technology"> Java for in-flight entertainment<BR> </tags:display> </TD><TD> <tags:display color="#ffcc11" bgcolor="#ffffcc" title="Sports"> American Football<BR/> </tags:display> </TD></TR> </TABLE>
  • I18N capable formatting tag library http://java.sun.com/jstl/fmt
  • Internationalization (i18n) Actions
  • I18N Key Concepts • Three internationalization key concepts: – Locale • Language code (e.g. “ca” for Catalan, “zh” for Chinese) • Optional country code (e.g.“IT” for Italy, “CR” for Costa Rica). – Resource bundle - contains locale-specific objects. A specific resource bundle is uniquely identified by combining its basename with a locale. – Basename – Identifies resource bundle group
  • I18N Key Concepts • E.g. basename Registration • two resource bundles: – Registration_fr (French language) – Registration_en (English language).
  • <fmt:message> • <fmt:message> - I18N a message – <fmt:param> - Supports message variables.
  • <fmt:message> <fmt:message key="greeting"/> ------------------------------------------------ --- <fmt:message key="athletesRegistered"> <fmt:param> <fmt:formatNumber value=”${athletesCount}”/> </fmt:param> </fmt:message>
  • I18n Localization Context • Localization context contains two pieces of information – Resource bundle – Locale for which the resource bundle was found. • i18n localization is determined in one of several ways: – <fmt:message> bundle attribute – Enclosing <fmt:bundle> action and basename attribute – I18n default localization context • javax.servlet.jsp.jstl.fmt.localizationContext configuration setting. – type LocalizationContext – type String.
  • I18n Localization Context <%-- Use configuration setting --%> ---------------------------------------------------------------------- --- <fmt:message key="Welcome" /> ---------------------------------------------------------------------- --- <fmt:setBundle basename="Errors" var="errorBundle" /> ---------------------------------------------------------------------- --- <fmt:bundle basename="Greetings"> <%-- Localization context established by parent <fmt:bundle> tag --%> <fmt:message key="Welcome" /> <%-- Localization context established by attribute bundle --%> <fmt:message key="WrongPassword" bundle="${errorBundle}" /> </fmt:bundle>
  • Preferred Locales • Setting prefered locale by – Application-based (priority) •javax.servlet.jsp.jstl.fmt.locale configuration setting – Browser-based • browser settings – ServletRequest.getLocales()
  • Preferred Locales • <fmt:setLocale> - set javax.servlet.jsp.jstl.fmt.loca le configuration variable – E.g. •<fmt:setLocale value=”en_US” />
  • Resource Bundle Lookup • Searched in the following order: – basename + "_" + language + "_" + country + "_" + variant – basename + "_" + language + "_" + country – basename + "_" + language
  • Resource Bundle Determination Algorithm • Step 1: Find a match within the ordered set of preferred locales • Step 2: Find a match with the fallback locale: javax.servlet.jsp.jstl.fmt.fall backLocale • load the root resource bundle with the given basename
  • Response Encoding • Set the locale – <fmt:setLocale> – <fmt:bundle> – <fmt:message> – formatting actions • Set the encoding – <fmt:requestEncoding>
  • Commands Summary • <fmt:setLocale> - stores the locale. Disables Browser-based locale setting capabilities. • <fmt:bundle> - Creates i18n context to be used by its body content • <fmt:setBundle> - creates an i18n context
  • Commands Summary • <fmt:message> • <fmt:param> - param to containing <fmt:message> • <fmt:requestEncoding> - character encoding
  • Configuration Settings
  • Configuration Settings
  • Formatting Actions
  • Formatting Actions • Format and parse elements in a locale- sensitive or customized manner
  • Formatting Numbers, Currencies, and Percentages • <fmt:formatNumber> - format numbers, currencies, and percentages according to the client’s cultural formatting conventions. • <fmt:formatNumber value="9876543.21" type="currency"/> • <fmt:formatNumber value="12.3" pattern=".000"/> • <fmt:formatNumber value="123456.7891" pattern="#,#00.0#"/> • <fmt:formatNumber value="123456789" type="currency" var="cur"/> • <fmt:parseNumber value="${cur}" type="currency"/>
  • Formatting Dates and Times • <jsp:useBean id="now" class="java.util.Date" /> • <fmt:formatDate value=”${now}” timeStyle="long" • dateStyle="long"/> • <fmt:formatDate value=”${now}” pattern="dd.MM.yy"/> • <fmt:timeZone value="GMT+1:00"> • <fmt:formatDate value=”${now}” type="both" dateStyle="full" • timeStyle="full"/> • </fmt:timeZone>
  • Formatting Locale • <jsp:useBean id="now" class="java.util.Date" /> • <%-- Formatting locale lookup --%> • <fmt:formatDate value=”${now}” /> • <fmt:bundle basename="Greetings"> • <%-- I18n localization context from parent <fmt:bundle> tag --%> • <fmt:message key="Welcome" /> • <fmt:formatDate value=”${now}” /> • </fmt:bundle>
  • Actions • <fmt:timeZone> • <fmt:timeZone value=”timeZone”> • body content • </fmt:timeZone> • <fmt:setTimeZone> • <fmt:setTimeZone value=”timeZone” • [var=”varName”] • [scope=”{page|request|session|application}”]/> • <fmt:formatDate> • <fmt:parseDate>
  • Configuration Settings
  • Functions function tag library
  • Functions • fn:contains • fn:containsIgnoreCase • fn:endsWith • fn:escapeXml • fn:indexOf • fn:join • fn:length • fn:replace • fn:split • fn:startsWith • fn:substring • fn:substringAfter • fn:substringBefore • fn:toLowerCase • fn:toUpperCase • fn:trim
  • JSTL 1.2 • <c:forTokens> • <x:param> - Set transformation parameters.
  • Conclusion • Simpler consistent programming environment. • Advanced programmers may prefer scriptlets. • JavaBeans are used in conjunction with JSTL. • Easier to develop and maintain.
  • For More Information • Fast Track JSP 1.2 • JavaServer Pages Technology • JavaServer Pages Specification (JSR 152) • The Tomcat 5 Servlet/JSP Container • JSP Developers Forum • JavaServer Pages Standard Tag Library (JSTL) • Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0)