The JSP Standard Tag G Library (JSTL) : Handling Variable Length Data Handling Variable-Length Data in MVC-Based JSP Pages
The JSP Standard Tag G Library (JSTL) : Handling Variable Length Data Handling Variable-Length Data in MVC-Based JSP Pages
The JSP Standard Tag G Library (JSTL) : Handling Variable Length Data Handling Variable-Length Data in MVC-Based JSP Pages
Overview and
Installation
Downloading JSTL
• JSTL 1.1
– Home
H page
• http://jakarta.apache.org/taglibs/doc/
standard-doc/intro.html
– Download
D l d
• http://jakarta.apache.org/site/downloads/
downloads_taglibs-standard.cgi
– Documentation
D t ti (Javadoc)
(J d )
• http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
– Note
• Many server packages (e.g., MyFaces) and IDEs (e.g.,
MyEclipse) already have JSTL 1.1 bundled
• JSTL 1.2
– As of 10/2008, only available as part of Java EE 5
• Not as a separate download for use in other servers
11
Enabling JSTL with Eclipse or
MyEclipse
• Eclipse
– Download from
Apache site
– Drag jstl.jar
jstl jar and
standard.jar They also
onto WEB-INF/lib show up here.
• Th
They also
l gett listed
li t d iin You drop
them here.
“ Web App Libraries”
• I usually rename JAR
fil tto show
files h exactt version
i
• MyEclipse
– Follow Eclipse directions above,
above or
– File New Web Project,
12
select JSTL 1.1 option
13
The JSTL Expression Language
• Accessed via ${expression}
• Similar to JavaScript and XPath
• Provides shorthand notation to access:
– Attributes of standard servlet objects
– Bean properties
– Map,
Map List,
List and Array elements
• Is standard part of JSP 2.0 and 2.1
– In JSTL,
JSTL EL can be used only in attributes of JSTL tags
– In JSP 2.0, the EL can be used anywhere
• web.xml element and page directive attribute let you
disable the EL for backward compatibility
• EL covered in separate lecture
14
Iteration Tags
20
Looping with a Designated Step
Size
<%@ taglib prefix="c"
uri http://java.sun.com/jsp/jstl/core %>
uri="http://java.sun.com/jsp/jstl/core"%>
<UL>
<c:forEach
var="seconds"
begin="0"
end="${pageContext.session.maxInactiveInterval}"
step="100">
<LI>${seconds} seconds
seconds.
</c:forEach>
<LI>Timeout exceeded.
</UL>
21
• Note
– url-pattern in web.xml is /test-array
22
Looping Down Arrays
<%@ taglib prefix="c"
uri="http://java
uri= http://java.sun.com/jsp/jstl/core
sun com/jsp/jstl/core"%>
%>
<H2>Key Words:</H2>
<UL>
<c:forEach var="word"
var= word
items="${words}">
<LI>${word}
</c:forEach>
</UL>
<H2>Values
a ues o
of t
the
e test Parameter:</H2>
a a ete : /
<UL>
<c:forEach var="val"
${p }
items="${paramValues.test}">
<LI>${val}
</c:forEach>
23 </UL>
25
30
Loop Status
• You can assign varStatus
– <c:forEach var="name" items="${names}"
varStatus="status">
• You can check status.subProperty
status subProperty
– Usually using c:if (covered later in this lecture)
• Status subproperties
– index (int: the current index)
– first (boolean: is this the first entry?)
– last (boolean: is this the first entry?)
– begin (Integer: value of 'begin' attribute)
– endd (Integer:
(I t value
l off end'd' attribute)
tt ib t )
– step (Integer: value of 'step' attribute)
31
32
Looping Down Comma-
Delimited Strings
<%@ taglib prefix="c"
uri="http://java
uri http://java.sun.com/jsp/jstl/core
sun com/jsp/jstl/core"%>
%>
<UL>
<c:forEach
y
var="country"
items="Australia,Canada,Japan,Philippines,Mexico,USA">
<LI>${country}
</c:forEach>
</UL>
33
Original Version
• In “Ajax Data Handling” lecture, showed example
that displayed lists of cities
– JavaScript
• Sent out request to server
• Took data back in XML,
XML JSON,
JSON or string format
• Extracted information and produced HTML table
• Inserted table into page
– HTML
• Loaded JavaScript files
• Had button that trigged the action
– Servlet
• Produced
P d d Li
Listt off Cit
City objects
bj t
– JSP
• Put city info into XML, JSON, or string format
– Repeated entries for each city in List
– Notes and source code for original example
• http://courses.coreservlets.com/Course-Materials/ajax.html
36
HTML Code
...
<fieldset>
<legend>Getting XML Data from Server...</legend>
<form action="#">
<label for="city-type-1">City Type:</label>
<select id="city-type-1">
id "city type 1">
<option value="top-5-cities">
Largest Five US Cities</option>
<option value="second-5-cities">
Second Five US Cities</option>
...
</select>
<br/>
<input type="button" value="Show Cities"
onclick='xmlCityTable("city-type-1",
"xml-city-table")'/>
</form>
<p/>
<div id="xml-city-table"></div>
37
</fieldset>...
Servlet Code
public class ShowCities extends HttpServlet {
public void doGet(HttpServletRequest
p ( p q request,
q ,
HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response setHeader("Pragma" "no
response.setHeader("Pragma", "no-cache");
cache");
String cityType = request.getParameter("cityType");
List<City> cities = findCities(cityType);
request.setAttribute("cities", cities);
String format = request.getParameter("format");
String outputPage;
if ("xml".equals(format)) {
response setContentType("text/xml");
response.setContentType( text/xml );
outputPage = "/WEB-INF/results/cities-xml.jsp";
} ...
RequestDispatcher dispatcher =
request.getRequestDispatcher(outputPage);
dispatcher.include(request, response);
}
38
Original JSP Code
(before-jstl/cities-xml
(before jstl/cities xml.jsp)
jsp)
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<headings>
<heading>City</heading>
<heading>Time</heading>
<heading>Population</heading>
</headings>
<city>
<name>${cities[0].name}</name>
{ [ ] }
<time>${cities[0].shortTime}</time>
<population>${cities[0].population}</population>
</city>
... <! Repeated for cities 1
<!– 1, 2
2, and 3 -->
>
<city>
<name>${cities[4].name}</name>
<time>${cities[4].shortTime}</time>
<population>${cities[4].population}</population>
</city>
</cities>
39
40
Updated JSP Code
(cities-xml
(cities xml.jsp)
jsp)
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<headings>
<heading>City</heading>
<heading>Time</heading>
<heading>Population</heading>
</headings>
<%@ taglib prefix="c"
prefix c
uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="city" items="${cities}">
<city>
c ty
<name>${city.name}</name>
<time>${city.shortTime}</time>
<population>${city.population}</population>
p p ${ y p p } /p p
</city>
</c:forEach>
41 </cities>
Alternative Version
(Using XML Syntax: cities
cities-xml
xml.jspx)
jspx)
<?xml version="1.0" encoding="UTF-8"?>
<cities xmlns:c=
xmlns:c="http://java
http://java.sun.com/jsp/jstl/core
sun com/jsp/jstl/core">
>
<headings>
<heading>City</heading>
<heading>Time</heading>
<heading>Population</heading>
</headings>
<c:forEach var="city"
var city items
items="${cities}">
${cities} >
<city>
<name>${city.name}</name>
<time>${city.shortTime}</time>
t e ${c ty.s o t e} /t e
<population>${city.population}</population>
</city>
</c:forEach>
/
</cities>
42
XML Data: Results
43
44
JSON Version: Updated
(cities-json
(cities json.jsp)
jsp)
<%@ taglib prefix="c"
uri="http://java
uri= http://java.sun.com/jsp/jstl/core
sun com/jsp/jstl/core" %>
{ headings: ["City", "Time", "Population"],
cities: [
<c:forEach var="city"
var city items
items="${cities}"
${cities} varStatus
varStatus="status">
status >
["${city.name}","${city.shortTime}","${city.population}"]
<c:if test="${!status.last}">,</c:if>
</c:forEach>
/
]
}
This is important because Internet Explorer
crashes for arrays and JSON objects with
trailing commas. E.g., these crash in IE:
var nums = [1, 2, 3, ];
var obj = { a: 1, b: 2, c: 3, };
45
46
Delimited String Version: Original
(before-jstl/cities-string
(before jstl/cities string.jsp)
jsp)
City#Time#Population
${cities[0] name}#${cities[0] shortTime}#${cities[0] population}
${cities[0].name}#${cities[0].shortTime}#${cities[0].population}
${cities[1].name}#${cities[1].shortTime}#${cities[1].population}
${cities[2].name}#${cities[2].shortTime}#${cities[2].population}
${cities[3] name}#${cities[3] shortTime}#${cities[3] population}
${cities[3].name}#${cities[3].shortTime}#${cities[3].population}
${cities[4].name}#${cities[4].shortTime}#${cities[4].population}
47
48
String Version: Results
49
Logic Tags
52
The "choose" Tag
<%@ taglib prefix="c"
p //j /j p/j /
uri="http://java.sun.com/jsp/jstl/core"%>
<UL>
<c:forEach var="i" begin="1" end="10">
<LI>${i}
<c:choose>
<c:when test="${i < 4}">
(small)
</c:when>
<c:when test="${i < 8}">
(medium)
</c:when>
<c:otherwise>
(large)
</c:otherwise>
</c:choose>
</c:forEach>
/
</UL>
53
59
60
Using Microsoft Access via
ODBC (Continued)
• Select Microsoft Access Driver, Finish, type
a name under
d Data
D S
Source N
Name, and d hit
hi
Select
61
62
Using Microsoft Access via
ODBC (Continued)
• Driver
– sun.jdbc.odbc.JdbcOdbcDriver
• Comes bundled with JDK
• URL
– jdbc:odbc:Northwind
• Local access only;
y for testing.
g Not for serious applications.
• Username
– Empty string
• Password
– Empty string
63
sql:setDataSource
• You can set a data source globally via
configuration
fi i settings
i or application-scoped
li i d
variables.
– Preferred approach in real applications
• Or, you can set it on a specific page
<%@ taglib
g p
prefix="sql"
q
uri="http://java.sun.com/jstl/sql" %>
<sql:setDataSource
driver="sun.jdbc.odbc.JdbcOdbcDriver"
j
url="jdbc:odbc:Northwind"
user=""
password
password=""/>
/>
64
sql:query
• Form 1: use the sql attribute
<sql:query var="results" sql="SELECT * FROM …"/>
• Form 2: put the query in the body of the tag
<sql:query var="results">
var "results">
SELECT * FROM …
</sql:query>
• Options
– dataSource
– maxRows
– startRow
• Caution
– Embedding SQL directly in JSP may be hard to maintain.
65
Simple Example
<%@ taglib prefix="c"
uri="http://java
uri= http://java.sun.com/jsp/jstl/core
sun com/jsp/jstl/core"%>
%>
<%@ taglib prefix="sql"
uri="http://java.sun.com/jstl/sql" %>
<sql:setDataSource
driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:Northwind"
user=""
""
password=""/>
66
Simple Example (Continued)
<sql:query var="employees">
SELECT * FROM employees
</sql:query>
<UL>
<c:forEach var="row" items="${employees.rows}">
<LI>${row.firstname}
${row.lastname}
</c:forEach>
/
</UL>
67
68
© 2009 Marty Hall
Other Tags
URL-Handling Tags
• <c:import>
– Read content from arbitrary URLs
• Insert into page
• Store in variable
• Or make accessible via a reader
– Unlike <jsp:include>, not restricted to own system
• <c:redirect>
di
– Redirects response to specified URL
• <c:param>
– Encodes a request parameter and adds it to a URL
– May be used within body of <c:import> or <c:redirect>
70
Formatting Tags
• <fmt:formatNumber>
– Formats a numeric value as a number, currency value, or
percent, in a locale-specific manner
• <fmt:parseNumber>
– Reads string representations of number, currency value,
or percent
p
• <fmt:formatDate>
• <fmt:parseDate>
• <fmt:timeZone>
• <fmt:setTimeZone>
71
72
XML Manipulation Tags
• Core
– <x:parse>
• XPath
– <x:if>
if
– <x:choose>
– <x:when>
– <x:otherwise>
– <x:forEach>
• XSLT
– <x:transform>
– <x:param>
73
Summary
• JSTL overview
– JSTL is
i similar
i il to the
h oldld Struts
S looping
l i andd logic
l i tags, but
b better
b
– JSTL is standardized, but not a standard part of JSP
• You have to add JAR files to WEB-INF/lib
• It is
i supposed
d tto b
be iincluded
l d d with
ith allll JSF iimplementations
l t ti
• Supports a concise expression language
– Lets you access bean properties and implicit objects
– EL is standard part of JSP 2.0, JSP 2.1, and JSF
• Looping tags
– Explicit numeric values
– Arrays, collections, maps, strings, etc.
• Conditional evaluation tags
– Single options
– Multiple options
74
Summary (Continued)
• Database Access Tags
– Always a bad idea when using MVC approach
• With or without a framework like JSF or Struts
– sql:setDataSource to specify a database
– sql:query to perform query
– Loop down results using iteration tags
• Other tags
– Handling URLS
– Internationalizing pages
– Formatting strings
– Manipulating XML
• Bad idea when using MVC
75
Questions?