Download - JSTL NOTLARI
-
8/14/2019 JSTL NOTLARI
1/94
1
1
JSTL (JSP Standard
Tag Library)
In this session, we are going to learn about JSTL (JSP Standard TagLibrary). We learned about custom tags in the previous session and howcustom tags are used within a JSP based Web applications. JSTL isbasically a standard set of custom tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
2/94
2
2
Sang Shin
JavaTechnology EvangelistSun Microsystems, Inc.
08/29/2006
-
8/14/2019 JSTL NOTLARI
3/94
3
3
Revision History
? 11/01/2003: version 1: created by Sang Shin? Things to do
speaker notes need to be polished
there are still some topics that are not covered yet
08/29/2006
-
8/14/2019 JSTL NOTLARI
4/94
4
4
Agenda? What is and Why JSTL?
? JSTL Functional areas Core tags
Database Access tags
XML tags? Quick review on XPath
Internationalization and Text Formatting tags
EL (Expression Language) functions tags
So what are we going to talk about in this session?
First, we will talk a little bit on what is and why you want to use JSTL? Thenwe will go over the JSTL tags which are categorized into 5 functional areas asmentioned above in the slide. As for XML tags, since understanding XPathexpression is important, we will spend some time going over important aspectsof XPath. At the end, we will also talk about JSTL roadmap.
08/29/2006
-
8/14/2019 JSTL NOTLARI
5/94
5
5
What is &
Why JSTL?
So let's talk about what is and why you want to use leverage with JSTL inyour Web application.
08/29/2006
-
8/14/2019 JSTL NOTLARI
6/94
6
6
What is JSTL?? Standard set of tag libraries? Encapsulates core functionality common to
many JSP applications iteration and conditionals XML database access
internationalized formatting? Likely to evolve to add more commonly
used tags in future versions
The JavaServer Pages Standard Tag Library (JSTL) is a standard set ofcommonly used tag libraries.
That is, JSTL encapsulates core functionality common to many JSPapplications. For example, instead of iterating over lists using a scriptlet ordifferent iteration tags from numerous vendors, JSTL defines a standard set ofiteration tags.
JSTL has tags for common structural tasks such as iteration and conditionals,
tags for manipulating XML documents, internationalization tags, and tags foraccessing databases using SQL.
08/29/2006
-
8/14/2019 JSTL NOTLARI
7/94
7
7
Why JSTL?? You don't have to write them yourself? You learn and use a single standard set of
tag libraries that are already provided bycompliant Java EE platforms
? Vendors are likely to provide moreoptimized implementation
? Portability of your applications are enabled
Even though it should obvious why you want to use JSTL, let's go over themanyway. To your JSP application, JSTL is what standard Java library is to yourJava application.
First and foremost, you don't have to write them yourself. Instead, you learnand use a single standard set of tag libraries that should be provided by allcompliant J2EE platforms. Furthermore, vendors are expected to provide moreoptimized implementations for these tags than the ones you would writeyourself. And of course, portability of you JSP applications are also enabled.
08/29/2006
-
8/14/2019 JSTL NOTLARI
8/94
8
8
JSTL Tag Libraries? Core (prefix: c)
Variable support, Flow control, URL management? XML (prefix: x)
Core, Flow control, Transformation
? Internationalization (i18n) (prefix: fmt) Locale, Message formatting, Number and date
formatting
? Database (prefix: sql) SQL query and update
? Functions (prefix: fn) Collection length, String manipulation
So JSTL 1.1 have categorized the standard tags into 5 different functionalareas- core tags, XML tags, Internationalization and formatting tags, databasetags, and functions tags. Each tag category has its own prefix convention asmentioned in the slide.
In the rest of this presentation, we will look into each of these tag categories.By the way, in this presentation, we will use example JSP pages that areprovided in Java WSDP tutorial.
08/29/2006
-
8/14/2019 JSTL NOTLARI
9/94
9
9
Declaration of JSTL Tag Libraries
? Core
? XML
? Internationalization (i18n)
? Database (SQL)
? Functions
This slide shows taglib declarations of the JSTL tag libraries. Please note thedifferent values of prefix attribute and uri attribute for each tag library.
08/29/2006
-
8/14/2019 JSTL NOTLARI
10/94
10
10
Core Tags
(Core Actions)
Now let's look into core tags. By the way, the terms tags and Actionsare used interchangeably.
08/29/2006
-
8/14/2019 JSTL NOTLARI
11/94
11
11
Core Tags Types (page 1)? Variable support
? Conditional
?
?
? Iteration
Core tags themselves are categorized into several types - tags that are used forsetting and removing scoped variable, conditional tags such as , iterationtags such as .
08/29/2006
-
8/14/2019 JSTL NOTLARI
12/94
12
12
Core Tags Types (page 2)? URL management
?
?
?
? General purpose
The core tags also include tags that are used for URL management such asURL rewriting. And then there are general purpose tags such as and. So let's go over each of these in a bit more detail.
08/29/2006
-
8/14/2019 JSTL NOTLARI
13/94
13
13
Variable Support, ? Sets the value of an EL variable or the
property of an EL variable via varattribute in any of the JSP scopes via scopeattribute page, request, session, application
? If the variable does not already exist, it getscreated and saved (in the scope object)
? Variable can be set in 2 different ways
? example:
value to be set
The set tag sets the value of an EL variable or the property of an EL variable inany of the JSP scopes (page, request, session, application). The name of thevariable is set via var attribute and the scope of the variable is set via scopeattribute.
If the variable does not already exist, it is created.
The JSP EL variable or property can be set either from attribute value:
or from the body of the tag:
...
For example, the following sets a EL variable named bookId with the value ofthe request parameter named BookID:
08/29/2006
-
8/14/2019 JSTL NOTLARI
14/94
14
14
Example: definitionquoted from ./elsupport/Set.jsp
${customer.lastName}
no address specified
The content between and /c:setis saved as ${customerTable}.
This JSP fragment shows the usage of tag in which the body content ofthe is set as a value of scoped variable. This fragment is quoted fromin another JSP page.
In this example, a scoped variable named customerTable is set to the bodycontent between and tag. The scope is set to applicationthus any JSP page in the same application can have access to it. Now let's seehow this customerTabe is used in the following slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
15/94
15
15
Example: How a predefined VariablecustomerTable is used: ./elsupport/Set2.jsp
Using "customerTable" application scope attribute defined inSet.jsp a first time
Using "customerTable" application scope attribute defined inSet.jsp a second time
This JSP fragment shows the usage of tag displaying the value of ascoped variable customerTable that was set via tag in previous slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
16/94
16
16
Example: How a predefined VariablecustomerTable is used: ./elsupport/Set2.jsp
This is the result. The customerTable scope variable contains the JSPfragment that contains table definition and it gets displayed here.
08/29/2006
-
8/14/2019 JSTL NOTLARI
17/94
17
17
Variable Support ? Remove an EL variable
To remove an EL variable, you use the remove tag. When the bookstore JSPpage bookreceipt.jsp is invoked, the shopping session is finished, so the cartsession attribute is removed as follows:
08/29/2006
-
8/14/2019 JSTL NOTLARI
18/94
18
18
Conditional Tags? Flow control tags eliminate the need for
scriptlets Without conditional tags, a page author mustgenerally resort to using scriptlets in JSP page
? Conditional execution of its body according to
value of a test attribute?
Performs conditional block execution by theembedded and sub tags
Works like if-then-else
In a vanilla JSP page, in order to execute flow control logic, a page author mustgenerally resort to using scriptlet. Flow control tags eliminate the need forscriptlets.
The tag allows the conditional execution of its body according to valueof a test attribute.
The tag performs conditional block execution by the embedded sub tags. It renders the body of the first tag whose test
condition evaluates to true. If none of the test conditions of nested when tagsevaluate to true, then the body of an tag is evaluated, if present.The , , and tags can be used to construct anif-then-else logic.
08/29/2006
-
8/14/2019 JSTL NOTLARI
19/94
19
19
Example: , ./conditionals/If.jsp
${customer}
Only the customers whose address.country propertyvalue is USA are displayed through loop.
This JSP fragment shows the usage of tag. Here only the customerswhose address.country property value is USA are displayed through loop. By the way, in this example, the scoped variablecustomers has been set when the application is loaded into the container.
08/29/2006
-
8/14/2019 JSTL NOTLARI
20/94
20
20
Example: , ./conditionals/Choose.jsp
${customer}
This slide shows JSP fragment in which tag and its sub tags and are used. Here the font color is set differentlydepending on the value of address.country property of a customer.
08/29/2006
-
8/14/2019 JSTL NOTLARI
21/94
-
8/14/2019 JSTL NOTLARI
22/94
22
22
Example: quoted from ./iterators/Simple.jsp
${customer}
This example shows iteration of customers from scope variable customers.
08/29/2006
-
8/14/2019 JSTL NOTLARI
23/94
23
23
Example: , Rangequoted from ./iterators/SimpleRange.jsp
${i}
Another simple iteration example. Similar to the previous one, except that inthis case there is no collection to iterate over. The items attribute is optional inthe tag. When it is not specified, the range attributes must be usedto iterate a specific number of times over the tag's body. In this example, wesimply iterate over the integer values specified by the range attributes.
08/29/2006
-
8/14/2019 JSTL NOTLARI
24/94
24
24
Example: , Data typesquoted from ./iterators/DataTypes.jsp
=
The tag supports a large number of data types for the collection ofobjects to iterate over. In this example, we feature the following data types:array of primitives, array of objects, Enumeration, Properties (Map), String(Comma Separated Values).
08/29/2006
-
8/14/2019 JSTL NOTLARI
25/94
25
25
Example: , Data typesquoted from ./iterators/DataTypes.jsp
This is the result of the previous page.
08/29/2006
-
8/14/2019 JSTL NOTLARI
26/94
26
26
Example: , Iteration statusquoted from ./iterators/Status.jsp
...
begin:beginend:end
step:step
sequence:...
The tag exposes a wealth of information relative to the iterationtaking place. This example features some of that status information.
08/29/2006
-
8/14/2019 JSTL NOTLARI
27/94
27
27
Example: , Iteration statusquoted from ./iterators/Status.jsp
This page shows the result of executing the JSP page shown in previous slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
28/94
28
28
Example:
This example features used with default values using the defaultattribute as well as the tag's body content.
08/29/2006
-
8/14/2019 JSTL NOTLARI
29/94
29
29
Example: quoted from /elsupport/Out.jsp
no cell phone specified
This example features used with default values using the defaultattribute as well as the tag's body content.
08/29/2006
-
8/14/2019 JSTL NOTLARI
30/94
30
30
Example: quoted from /elsupport/Out.jsp
This page shows the result of executing JSP page shown in previous slide.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
31/94
31
31
URL Import: ? More generic way to access URL-based
resources (than ) Absolute URL: for accessing resources outside of
Web application
Relative URL: for accessing resources inside ofthe same Web application
? More efficient (than ) No buffering
? tag can be used to specifyparameters (like )
The element provides for the inclusion of static and dynamicresources in the same context as the current page. However, cannot access resources that reside outside of the Web application and causesunnecessary buffering when the resource included is used by another element.
In the example below, the transform element uses the content of the includedresource as the input of its transformation. The element reads thecontent of the response, writes it to the body content of the enclosing transformelement, which then re-reads the exact same content. It would be more efficientif the transform element could access the input source directly and avoid thebuffering involved in the body content of the transform tag.
The tag is therefore the simple, generic way to access URL-basedresources whose content can then be included and or processed within the JSPpage.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
32/94
32
32
Example: Absolute URLquoted from /import/Absolute.jsp
This is JSP fragment which shows the usage of in whichabsolute URL address is used. Here the contents of the file that is referencedby the URL will be included.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
33/94
33
33
Example: with
This is JSP fragment which shows the usage of in whichabsolute URL address is used. Here the contents of the file that is referencedby the URL will be included.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
34/94
34
34
URL Rewriting: ? Used for URL rewriting
All the URL's that are returned from a JSP page(to a browser) have session ID if Cookie isdisabled on the browser
? Can take param subtags for includingparameters in the returned URL
In Session Tracking session of basic J2EE programming course, wediscussed how an application must rewrite URLs to enable session trackingwhenever the client turns off cookies. You can use the tag to rewriteURLs that are being returned from a JSP page. The tag includes the session IDin the URL only if cookies are disabled; otherwise, it returns the URLunchanged. Note that this feature requires the URL to be relative. The url tagtakes param subtags for including parameters in the returned URL.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
35/94
35
35
Example:
"base", param=ABC
"base", param=123
This is an example of tag usage. This page will be displayeddifferently depending on whether the client browser has disabled cookies ornot. So let's see how this works in the following two slides.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
36/94
36
36
Example: - Cookie enabledquoted from /import/Encode.jsp
This is the case where client's browser has cookies enabled. So the URLrewriting will send URL without session ID information postfixed to each URLthat is returned to the client.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
37/94
37
37
Example: - Cookie disabled
This is the case where client disabled cookies. Now you can see the URL thatis returned to the client has session ID attached.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
38/94
38
38
Redirection: ? Sends an HTTP redirect to the client?
Takes subtags for includingparameters in the returned URL
The redirect tag sends an HTTP redirect to the client. The redirect tag takesparam subtags for including parameters in the returned URL.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
39/94
39
39
? Evaluates an expression and outputs the
result of the evaluation to the current JspWriter
object? If the result of the evaluation is a
java.io.Reader object, data is first read fromthe Reader object and then written into thecurrent JspWriter object improved performance
? Syntax If escapeXml is true, escape character conversion
The out tag evaluates an expression and outputs the result of the evaluation tothe current JspWriter object. The syntax and attributes are
If the result of the evaluation is a java.io.Reader object, data is first read fromthe Reader object and then written into the current JspWriter object. Thespecial processing associated with Reader objects improves performance whenlarge amount of data must be read and then written to the response.
If escapeXml is true, the character conversions as following are applied. Thisconversion will allow these characters which have special meaning underXML to be displayed as characters.
Character Character Entity Code< >& &' '" "
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
40/94
40
40
Example: quoted from /elsupport/Out.jsp
no cell phone specified
This is an example of tag. Here we are displaying customer's lastname, phone number, and cell phone number in a table format.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
41/94
41
41
Example: quoted from /elsupport/Out.jsp with Reader objectReader1 (escapeXml=true) :
Reader2 (escapeXml=false):This is an example of tag usage in which the result of evaluation isjava.Io.Reader object. We are also showing the usage of escapeXML attribute.The same content Text for a Reader is displayed withescapeXML is set to true and then false.
08/29/2006
08/29/2006
-
8/14/2019 JSTL NOTLARI
42/94
42
42
Example: quoted from /elsupport/Out.jsp
This is the result.
08/ 9/ 006
08/29/2006
-
8/14/2019 JSTL NOTLARI
43/94
43
43
Database Access Tags
(SQL Tags)
Now let's talk about SQL tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
44/94
44
44
.jsp
Database
SQL
RAD/Prototyping/Simple Apps
The JSTL SQL tags are designed for quick prototyping and simpleapplications. For production applications, database operations arenormally encapsulated in JavaBeans components through MVC pattern asshown in the following slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
45/94
45
45
.jsp
Database
Dynamic Content
MVC Architecture
SQLBeans
Business Logic
So in production environment, the database access logic is typicallycaptured within JavaBeans which functions as a Model under MVCarchitecture. This state of the JavaBeans is set by the Controller (Servlet)and then is accessed by the JSP pages (View).
Again accessing database directly using SQL tags is NOT following thisMVC pattern, thus the reason why usage of SQL tags within JSP pagesare usually reserved for simple prototyping situations.
08/29/2006
-
8/14/2019 JSTL NOTLARI
46/94
46
46
.jsp
Database
SQL Tags
Query the database
Easy access to
result set
Result
ResultSupport
Update the database
SQL tags that are supported include for querying and for creating and updating database table
08/29/2006
-
8/14/2019 JSTL NOTLARI
47/94
47
47
DataSource
? All DB actions operate on a DataSource? Different ways to access a DataSource
Object provided by application logic
Object provided by action
The setDataSource tag is provided to allow you to set data sourceinformation for the database. You can provide a JNDI name orDriverManager parameters to set the data source information.
08/29/2006
-
8/14/2019 JSTL NOTLARI
48/94
48
48
Example:
for setting a table using PointBase
So using tag, you can set your JDBC driver and URLof your database. Here in this example, you are setting these two for adatabase table that is to be created in PointBase database server.
08/29/2006
-
8/14/2019 JSTL NOTLARI
49/94
49
49
Example: & from /sql/QueryDirect.jsp
create table mytable (
nameid int primary key,name varchar(80)
)
INSERT INTO mytable VALUES (1,'Paul Oakenfold')
INSERT INTO mytable VALUES (2,'Timo Maas')...
SELECT * FROM mytable
This example shows the creation of a very simple database and then populatingthe table. Then querying the database table and save the query result into ascope variable deejays.
By the way, it is expected that you started the PointBase database server andalso DataSource has been set. Otherwise, you will experience HTTP 500 errorcondition.
08/29/2006
-
8/14/2019 JSTL NOTLARI
50/94
50
50
Example: & from /sql/QueryDirect.jsp
This is the execution result of the JSP page of the previous page.
08/29/2006
-
8/14/2019 JSTL NOTLARI
51/94
51
51
XML Tags
Now let's talk about XML tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
52/94
52
52
XML Tags
? Flow control , , ,
? Iteration
? General purpose
? Parsing and Transformation
with subtags
This slide shows XML tags. As you can see, XML tags has flow control,iteration, and general purpose tags as in the Core tags. For parsing andtransformation, which are unique for XML tags, there are and tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
53/94
53
53
XML Tags
? Used to access information stored in XMLdocument
? Access description is specified in XPathexpression as a value of select attribute
? Flow control, Iteration, General purposeXML tags work similarly as correspondingtags in Core tags
XML tags are used to access information stored in XML document. Now whatis unique about XML tags is that the access description is specified in XPathexpression as a value of select attribute as shown in the slide above. Exceptthat the access description is described in XPath expression, the flow control,iteration, and general purpose tags work similarly as corresponding tags inCore tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
54/94
54
54
Quick XPathReview (Start)
Since understanding XPath is very important for understanding XML tags, let'sdo a quick overview of XPath.
08/29/2006
-
8/14/2019 JSTL NOTLARI
55/94
55
55
Example XML Document
Lux 1
swimming
23M
Den 1
cycling18
F
Den 2sailing27M
This slide shows an example XML document we are going to use in ourexplanation of XPath. Please quickly glance over this XML document. Thisexample is from JWSDP.
08/29/2006
-
8/14/2019 JSTL NOTLARI
56/94
56
56
What is XPath?
? XPath is an Expression Language forreferencing particular parts of XML
document? XPath expression uses a tree model to
represent a XML document XPath expression/games/country/athlete
evaluates to a node-set that contains all nodescorresponding to the athletes of all countries in thegames XML document
So what is XPath? XPath is an expression language for referencing particularparts of XML document. Now the XPath expression uses a very familiar treemodel to represent a XML document. For example, XPath expression /games/country/athlete evaluates to a node-set that contains all nodescorresponding to the athletes of all country's of the games in a XMLdocument. Now please note that we use a term node set here. This is animportant concept you need to understand, so let's spend sometime on it.
08/29/2006
-
8/14/2019 JSTL NOTLARI
57/94
57
57
XPath Expression Result DataTypes: 4 Data Types
? Node set
Type we will spend most time with? Boolean? Number? String
XPath expression result data type can be in one of the 4 data types - node set,boolean, number, and string. Among these, you will use the node set data typethe most. Now let's learn what a node set is in the following slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
58/94
58
58
Node Set, Location Path, LocationStep, Predicate
? A node-set is a collection of zero or more
nodes from XML document? A note-set is a return type from location path
expression? A location path expression is composed of
location steps? A Location step can be qualified with a
predicate/games/country/athlete[sport=sailing]
/games/country[@id=Demark]/athlete
As you might have guessed it, a node set is a collection of zero or more nodesfrom an XML document.
A node-set is a return type from location path expression such as /games/country. Each entry between the / (slash) is called location step. Soa location expression is composed of location steps delimited by /.
Each location step can be qualified with a predicate. For example, in thelocation expression example, /games/country/athlete[sport=sailing], theathlete location step is qualified with a predicate [sport=sailing], which
means athlete elements whose child element sport has a string valuesailing.
08/29/2006
-
8/14/2019 JSTL NOTLARI
59/94
59
59
Examples of Node Set
? /games/country/athlete all athlete elements which has country parent
element which in turn has games parent element? /games/country[1]/athlete[2]
the 2ndathlete element under 1stcountry element? /games/country/athlete[sport=sailing]
all athlete elements whose child element sport hasstring-value sailing
? /games/country[@id=Demark]/athlete all athlete elements whose parent element country
has id attribute value Denmark
Now let's go over some more XPath expression examples. Here we have 4examples. (please read the slide)
08/29/2006
-
8/14/2019 JSTL NOTLARI
60/94
60
60
Examples of Node Set
? /games/country/*
all child elements under /games/country? /games/country//sport
all sport elements in a subtree that begins with/games/country
(please read the slide)
08/29/2006
-
8/14/2019 JSTL NOTLARI
61/94
61
61
XPath Type Coercion (Conversion)
? XPath specification defines rules on hownode-set, boolean, number, string are to be
converted to each other? Note-set is converted to
boolean: true if note-set is not empty, falseotherwise
string: the string value of the first node in the node-set
? the reason why results inswimming
number: node-set is first coerced to a string, whichis then coerced to a number
Now let's talk about XPath type coercion. XPath specification defines rules onhow the 4 data types - node set, boolean, number, and string - can be convertedto each other. Since node-set is the most type you will convert to other types,let's go over it.
When node-set is converted to boolean type, the resulting value is true if thenode set is not empty, false otherwise. If a node set is converted to a string, thereturn value is the string value of the first node in the node set. As you will seelater on, this is the reason why results inswimming. (We will talk about this example again later on. So if you don't
understand this example, just move on.) When a node set is converted to anumber, basically the node set is converted to a string first, which is thenconverted to a number.
Now when do these type coercion occur? It depends. The node-set to stringconversion occur when tag is used. Node set to boolean type coercioncan occur when boolean function is used. (We have learn about these functionsin the next slide.)
08/29/2006
-
8/14/2019 JSTL NOTLARI
62/94
62
62
XPath Functions
? XPath expression can contain functions? Example
count(node-set): returns number of nodes in anode-set
? count(/games/country) returns 2 since there are 2country nodes in the node-set
id(object): selects a node with the specified id last(): returns size of the current node-set string functions
? string substring(/games/country, 1, 3)
boolean functions? boolean not(/games/country)
I briefly mentioned XPath functions in the previous slide. What is XPathfunctions? These are functions that can be applied to XPath expressions. Forexample, count(note-set) function returns the number of nodes in a node set.
Please note that there are string functions and boolean functions. These stringfunctions and boolean functions can take any one of the 4 data types - node set,boolean, string, number -, hence the need for a rule of type conversion.
08/29/2006
-
8/14/2019 JSTL NOTLARI
63/94
63
63
Quick XPathReview (End)
OK. This is the end of the quick review of XPath. I hope you get some ideawhat XPath is. Now let's get back to XML tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
64/94
64
64
? Parse XML document into a scopedvariable
tag is for parsing XML document into a scoped varilable.
08/29/2006
-
8/14/2019 JSTL NOTLARI
65/94
65
65
Example: from /xml/Parse.jsp
foo
bar
In this example which I quoted from ./xml/Parse.jsp of JWSDP, we are XMLdata into a variable called xmlTest. This XML data is then parsed into avariable called a.
Now $a//c returns a node set which contains all c elements while $a/a/dreturns a node set which contains all d elements which has a parent elementa. As we will learn later on, tag returns string value of the node set,which means the string value of the first node in the node set.
08/29/2006
-
8/14/2019 JSTL NOTLARI
66/94
66
66
Example: from /xml/Parse.jsp
This slide shows the result of running the Parse.jsp page. As expected,the returns foo through the following logic:
(1) select=$a//c returns a node set which contains all the c elements inthis XML document. In this example, there is only one c element foo .(2) then returns the string value of the node set. The stringvalue of a node set is the string value of the first node in the node set. Inthis example, the first node (and the only node) is foo and thestring value is foo.
The works in a similar way
(1) select=$a/a/d returns a node set which contains all the d elementswhich has a as parent element. In this example, there is only oneelement that fits this pattern.(2) then returns the string value of the node set. In this case, it isbar.
08/29/2006
-
8/14/2019 JSTL NOTLARI
67/94
67
67
? Works like tag? tag converts node-set type to a
String type the string value of the first node in the node-set The string value of an element is the
concatenation of all descendent text nodes, nomatter how deep
Example element String value
Lux 1 Lux 1swimming swimming23 23M M
OK, we already talked about tag. As mentioned before, tagworks like tag, again except the fact that the access description is inthe form of XPath expression.
tag converts node set type to a string type. As mentioned a couple oftimes already, when node set is converted to a string type, the resulting value isthe string value of the first node in the node set.
Now a string value of an element is the concatenation of all the child text nodesno matter how deep it is. The example shown above illustrates this. The
element has several child elements. And the string value of this element is the concatenation of all the texts of its child elements.
08/29/2006
-
8/14/2019 JSTL NOTLARI
68/94
68
68
Example: from /xml/Out.jsp
$doc//sport
$doc/games/country/*
$doc//*
$doc/games/country
Now I would like to go over ./xml/Out.jsp example of the JWSDP. This containsvarious tag examples. This slide shows the first part of the Out.jsp page.
I am going to explain the first couple on this page. The first one is . The XPath expression $doc//sport returns a node set that containsall sport elements in this XML document. In this XML document, there are 4 sportelements - swimming, wrestling,cycling, sailing. Then converts the node setinto a string type. According to the conversion rule, the string value of the first node inthe node set is returned. And that is what you will see in the following captured screenof running Out.jsp page.
Same thing can be said for . In this case, the
XPath expression returns a node set that contains all child elements under /games/country, which means all 4 elements. Again converts thisnode set into a string type. And the string value of the first node will be returned, thusthe result you will see in the next slide.
08/29/2006
-
8/14/2019 JSTL NOTLARI
69/94
69
69
Example: from /xml/Out.jsp
This is the results of the running the Out.jsp page. Please spend some timegoing through the logic we have used in the previous slide for the remaining examples.
08/29/2006
-
8/14/2019 JSTL NOTLARI
70/94
70
70
Example: from /xml/Out.jsp
$doc/games/country[last()]
$doc//@id
$doc//country[@id='Denmark']
This is the latter part of Out.jsp which shows XPath expressions that haspredicates and addressing attributes.
08/29/2006
-
8/14/2019 JSTL NOTLARI
71/94
71
71
Example: from /xml/Out.jsp
This slide shows captured screen of running Out.jsp page of the previous page.
08/29/2006
-
8/14/2019 JSTL NOTLARI
72/94
72
72
Example: from /xml/Out.jsp
This slide shows the result of last tag.
08/29/2006
-
8/14/2019 JSTL NOTLARI
73/94
73
73
Access to built-in scopevariables in XPath expression? $foo
? $param:? $header:? $cookie:? $initParam:? $pageScope:? $requestScope:? $sessionScope:? $applicationScope:
In addition to the standard XPath syntax, the JSTL XPath engine supports thefollowing scopes to access Web application data within an XPath expression:
* $foo* $param:* $header:* $cookie:* $initParam:* $pageScope:* $requestScope:
* $sessionScope:* $applicationScope:
These scopes are defined in exactly the same way as their counterparts in theJSP expression language discussed in Implicit Objects
08/29/2006
-
8/14/2019 JSTL NOTLARI
74/94
74
74
Example: Access to built-inscope variables? $sessionScope:profile
The session-scoped EL variable named profile? $initParam:mycom.productId
The String value of the mycom.productId contextparameter
These are examples of XPath expressions in which scope variables are used.
08/29/2006
-
8/14/2019 JSTL NOTLARI
75/94
75
75
EL Functions
Now let's talk about EL functions. If you are familiar with Java stringfunctions, which I assume most of you are, then understanding ELfunctions is easy. It is standard string functions you can use in JSP page.
08/29/2006
-
8/14/2019 JSTL NOTLARI
76/94
76
76
EL Functions in JSTL 1.1? Length of collection of string? , Change the
capitalization of a string? , ,
Get a subset of a string? Trim a string? Replace characters in a string? , , ,
Check if a string containsanother string
? , Split a string into an array,and join acollection into a string
? Escape XML characters in the string
This slide shows the list of EL functions you can use.
08/29/2006
-
8/14/2019 JSTL NOTLARI
77/94
77
77
Example: EL Functions< %- - t r u n c a t e n a m e t o 3 0 c h a r s a n d d i s p l a y i t i n u pp e r c a s e - - %>$ { f n : t o Up p e r Ca s e ( f n : s u b s t r i n g ( n a me , 0 , 3 0 ) ) }
< %- - D i s p l a y t h e t e x t v a l u e p r i o r t o t h e f i r s t * c h a r a c t e r - - %>
$ { f n : s u b s t r i n g Be f o r e ( t e x t , * ) }
< %- - S c o p e d v a r i a b l e " n a me " ma y c o n t a i n wh i t e s p a c e s a t t h e
b e g i n ni n g o r e n d . T r i m i t f i r s t , o t h e r wi s e we e n d u p wi t h + ' s i n t h e U RL- - %>< c : u r l v a r = " my Ur l " v a l u e = " ${ b a s e } / c u s t / $ { f n : t r i m ( n a me ) } " / >
< %- - D i s p l a y t h e t e x t i n b e t w e e n b r a c k e t s - - %>
$ { f n : s u b s t r i n g ( t e x t , f n : i n d e x Of ( t e x t , ( ) + 1 , f n : i n d e x Of ( t e x t , ) ) ) }
< %- - D i s p l a y t h e n a me i f i t c o n t a i n s t h e s e a r c h s t r i n g - - %>< c : i f t e s t = " $ { f n : c o n t a i n s I g n o r e C a s e ( n a me , s e a r c h S t r i n g ) } " >
F o u n d n a me : $ { n a m e }< / c : i f >
< %- - D i s p l a y t h e l a s t 1 0 c h a r a c t e r s o f t h e t e x t v a l u e - - %>$ { f n : s u b s t r i n g ( t e x t , f n : l e n g t h ( t e x t ) - 1 0 ) }
< %- - D i s p l a y t e x t v a l u e wi t h b u l l e t s i n s t e a d o f - - - %>$ { f n : r e p l a c e ( t e x t , - , 1 4 9 ; ) }
This slide shows usage of EL functions.
08/29/2006
-
8/14/2019 JSTL NOTLARI
78/94
78
78
Internationalization (i18n)
&Text Formatting Tags
Now let's talk about internationalization and text formatting tags.
Internationalization is the process of preparing an application to supportmore than one language and data format. Localization is the process ofadapting an internationalized application to support a specific region orlocale. Examples of locale-dependent information include messages anduser interface labels, character sets and encoding, and date and currencyformats. Although all client user interfaces should be internationalized andlocalized, it is particularly important for Web applications because of theglobal nature of the Web.
08/29/2006
-
8/14/2019 JSTL NOTLARI
79/94
79
79
I18N and Formatting Tags
? Setting locale
? Messaging
with subtag
? Number and Date formatting ,
,
,
JSTL defines tags for: setting the locale for a page, creating locale-sensitivemessages, and formatting and parsing data elements such as numbers,currencies, dates, and times in a locale-sensitive or customized manner.
This slide shows the I18N and formatting related tags that are supported byJSTL.
08/29/2006
-
8/14/2019 JSTL NOTLARI
80/94
80
80
Quick I18NReview (Start)
Let's quickly overview I18N concept here.
08/29/2006
-
8/14/2019 JSTL NOTLARI
81/94
81
81
How Locale Is Set in Web app
Web ApplicationWorldwide Users
1. Request sensing
preferred locales
chinese,
spanish,
2. Application-based
loginsession
prefs
locales
This picture shows how locale preference can be set for a Webapplication. There are two different approaches - one that is based onclient locale preference that is sent as part of HTTP request, the otherapproach in which locale preference is determined by other factors such aslogin name. Here we are mainly concerned about the first approach.
So in the first approach, a client browser is typically configured with aparticular language preference - we will call this locale preference. Onceit is set, this locale preference is sent to the server as part of HTTPrequest.
A web application running on the server, when it receives the HTTPrequest that contains locale preference information, can either honor it oroverride it. In the servlet code, a Web application retrieves the clientlocale preference via getLocale() method of HTTPServerRequest object.
08/29/2006
-
8/14/2019 JSTL NOTLARI
82/94
82
82
I18N Architecture: Option 1
Web ApplicationWorldwide Users
1. One page per locale
controller
JSPch
JSPes
Messages and labels should be tailored according to the conventions of auser's language and region. There are two approaches to providinglocalized messages and labels in a Web application. We will take a lookat these two approaches here.
In the first approach, which you see on this slide, you provide a version ofthe JSP page in each of the target locales and have a controller servletdispatch the request to the appropriate page depending on the requestedlocale. This approach is useful if large amounts of data on a page or anentire Web application need to be internationalized.
08/29/2006
-
8/14/2019 JSTL NOTLARI
83/94
83
83
I18N Architecture: Option 2
Web ApplicationWorldwide Users
ch
JSP
es
Resource Bundles
2. One page for all locales
This is the 2nd approach. In this approach, you isolate any locale-sensitivedata on a page into resource bundles, and access the data so that thecorresponding translated message is fetched automatically and insertedinto the page. Thus, instead of creating strings directly in your code, youcreate a resource bundle that contains translations and read thetranslations from that bundle using the corresponding key. Using JSPI18N tags allows you to take this approach.
08/29/2006
-
8/14/2019 JSTL NOTLARI
84/94
84
84
Quick I18NReview (End)
This is the end of quick i18n review.
08/29/2006
-
8/14/2019 JSTL NOTLARI
85/94
85
85
Setting Locales
? Override client-specified locale for a page
? Set the request's character encoding, in order to be
able to correctly decode request parameter valueswhose encoding is different from ISO-8859-1
The tag is used to override the client-specified locale for apage. The tag is used to set the request's characterencoding, in order to be able to correctly decode request parameter valueswhose encoding is different from ISO-8859-1.
08/29/2006
-
8/14/2019 JSTL NOTLARI
86/94
86
86
Messaging Tags
? specify a resource bundle for a page
? used to output localized strings subtag provides a single argument
(for parametric replacement) to the compoundmessage or pattern in its parent message tag
The tag is used to output localized strings. The following tagfrom bookcatalog.jsp
is used to output a string inviting customers to choose a book from the catalog.
The param subtag provides a single argument (for parametric replacement) tothe compound message or pattern in its parent message tag. One param tagmust be specified for each variable in the compound message or pattern.
Parametric replacement takes place in the order of the param tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
87/94
87
87
Example:quoted from ./fmt/GermanLocale.jsp
greetingMorning
In this example, locale is set to de which is locale for Germany. And bundleis set. And then a German message whose key is greetingMorning isdisplayed.
08/29/2006
-
8/14/2019 JSTL NOTLARI
88/94
88
88
Example:
http://localhost:8080/webapps-jstl/format/GermanLocale.jsp
This is the result.
08/29/2006
-
8/14/2019 JSTL NOTLARI
89/94
89
89
Formatting Tags
? , used to output localized numbers and dates
? , used to parse localized numbers and dates
? , used to set and get timezone
JSTL provides a set of tags for parsing and formatting locale-sensitive numbersand dates.
The formatNumber tag is used to output localized numbers. The following tagfrom bookshowcart.jsp
is used to display a localized price for a book. Note that since the price ismaintained in the database in dollars, the localization is somewhat simplistic,
because the formatNumber tag is unaware of exchange rates. The tag formatscurrencies but does not convert them.
Analogous tags for formatting dates (formatDate), and parsing numbers anddates (parseNumber, parseDate) are also available. The timeZone tagestablishes the time zone (specified via the value attribute) to be used by anynested formatDate tags.
08/29/2006
-
8/14/2019 JSTL NOTLARI
90/94
90
90
Example:quoted from ./format/FormatDateTime.jsp
Formatting current date as "GMT":
Formatting current date as "GMT+1:00", and parsingits date and time components:
Parsed date:
Parsed time:This JSP fragment is quoted from FormatDataTime.jsp page of JWSDPtutorial. We will see the result of the running this page one using en-us Localepreference in the browser and the other resetting the browser Locale preferenceto Korean and then rerun the same page.
08/29/2006
-
8/14/2019 JSTL NOTLARI
91/94
91
91
Example: using browser locale en-usquoted from ./format/FormatDateTime.jsp
This is the result of running the page with default en-us Locale setting on mynetscape browser. As you can see, the format of date and time is en-us locale.
08/29/2006
-
8/14/2019 JSTL NOTLARI
92/94
92
92
Change Browser Locale preference toKorean
Now I added Korean (ko) Locale and make it as my default Locale setting onmy Netscape browser.
08/29/2006
-
8/14/2019 JSTL NOTLARI
93/94
93
93
Example: using browser locale koquoted from ./format/FormatDateTime.jsp
After rerunning the same page, this is what I get. The date and time is now inKorean Locale.
08/29/2006
-
8/14/2019 JSTL NOTLARI
94/94
94
94
Passion!