jstl guide

Tags:

Post on 13-May-2015

4.527 Views

Category:

Technology

12 Downloads

Preview:

Click to see full reader

DESCRIPTION

JSTL Tutorial

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 ContentpageScope access to the scoped variables

requestScope access to the scoped variablessessionScope access to the scoped variables

applicationScope access to the scoped variablesparam 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 requestpageContext 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 LibrariesFunctional

Area URI Prefix

core http://java.sun.com/jstl/core cXML processing http://java.sun.com/jstl/xml xI18N capable

formatting

http://java.sun.com/jstl/fmt fmt

relational db access (SQL)

http://java.sun.com/jstl/sql sql

RT-based Tag LibrariesFunctional

Area URI Prefix

core http://java.sun.com/jstl/core_rt c_rtXML processing http://java.sun.com/jstl/xml_rt x_rtI18N 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 Libraryhttp://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 Libraryhttp://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.dataSource.

– data source action:• JNDI relative path.• JDBC Parameters

Querying a Database

• <sql:query>

Querying a Database<sql:query var="customers" dataSource="${dataSource}">

SELECT * FROM customersWHERE 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 accountSET Balance = Balance - ?WHERE accountNo = ?<sql:param value="${transferAmount}"/><sql:param value="${accountFrom}"/>

</sql:update><sql:update>

UPDATE accountSET 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 PersonalInfoSET 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.SimpleTag interface.

• Define a tag descriptor in a TLD

• JSP page that uses the tag

Implementing SimpleTagpackage 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.locale 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.fallbackLocale

• 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)

top related