Chapter 09 Slides
Chapter 09 Slides
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Use the JSTL core library with EL to add functionality to JSPs.
2. Use the documentation for the JSTL libraries to learn about other
JSTL capabilities.
Knowledge
1. Describe the use of these JSTL tags: out, forEach, forToken, if,
choose, import, and url.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 2
The primary JSTL libraries
Name Prefix URI Description
Core c http://java.sun.com/jsp/jstl/core Core tags for common tasks
such as looping and if/else
statements.
Formatting fmt http://java.sun.com/jsp/jstl/fmt Tags for formatting
numbers, times, and dates so
they work correctly with
internationalization (i18n).
SQL sql http://java.sun.com/jsp/jstl/sql Tags for working with SQL
queries and data sources.
XML x http://java.sun.com/jsp/jstl/xml Tags for manipulating XML
documents.
Functions fn http://java.sun.com/jsp/jstl/functions Functions that can be used
to manipulate strings.
AJK Note: there is a Reusable Tag Library Validator (TLV) library also. It is used for XML validation.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 3
NetBeans with the JSTL 1.2 library added
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 4
An introduction to JSTL
The JSP Standard Tag Library (JSTL) provides tags for common
JSP tasks.
Before you can use JSTL tags within an application, you must
make the jstl-impl.jar and jstl-api.jar files available to the
application. To do that with NetBeans, you can add the JSTL 1.2
class library to your project.
Before you can use JSTL tags within a JSP, you must code a
taglib directive that identifies the JSTL library and its prefix.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 5
Browser that displays the JSTL documentation
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 7
How to escape output entered by the user
<label>Email:</label>
<span><c:out value="${user.email}" /></span><br>
<label>First Name:</label>
<span><c:out value="${user.firstName}" /></span><br>
<label>Last Name:</label>
<span><c:out value="${user.lastName}" /></span><br>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 8
How to escape output that displays cookies
<table>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<c:forEach var="cook" items="${cookie}">
<tr>
<td><c:out value="${cook.value.name}" /></td>
<td><c:out value="${cook.value.value}" /></td>
</tr>
</c:forEach>
</table>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 9
How to display a default value
Using the default attribute
<p><c:out value="${message}" default="No message" /></p>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 10
How to loop through a collection
<c:forEach var="item" items="${cart.items}">
<tr>
<td>${item.quantity}</td>
<td>${item.product.description}</td>
<td>${item.product.priceCurrencyFormat}</td>
<td>${item.totalCurrencyFormat}</td>
</tr>
</c:forEach>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 11
How to loop through a comma-delimited string
Servlet code
session.setAttribute("productCodes", "8601,pf01,pf02,jr01");
JSP code
<p>Product codes</p>
<ul>
<c:forTokens var="productCode" items="${productCodes}" delims="," >
<li>${productCode}</li>
</c:forTokens>
</ul>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 12
How to parse a string
Servlet code
session.setAttribute("emailAddress", "[email protected]");
JSP code
<p>Email parts</p>
<ul>
<c:forTokens var="part" items="${emailAddress}" delims="@.">
<li>${part}</li>
</c:forTokens>
</ul>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 13
Attributes for advanced loops
Attribute Description
begin Specifies the first index for the loop.
end Specifies the last index for the loop.
step Specifies the amount to increment the index each time
through the loop.
varStatus Specifies the name of a variable that can be used to
get information about the status of the loop. This
variable provides the first, last, index, and count
properties.
Note
If necessary, you can nest one loop within another.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 14
Servlet code that creates an array of numbers
int[] numbers = new int[30];
for (int i = 0; i < 30; i++) {
numbers[i] = i+1;
}
session.setAttribute("numbers", numbers);
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 15
JSP code that uses advanced attributes
<p>Numbers</p>
<ul>
<c:forEach items="${numbers}" var="number"
begin="0" end="9" step="1"
varStatus="status">
<li>${number} | First: ${status.first} | Last: ${status.last} |
Index: ${status.index} | Count: ${status.count} </li>
</c:forEach>
</ul>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 16
How to code an if statement
<c:if test="${cart.count == 1}">
<p>You have 1 item in your cart.</p>
</c:if>
<c:if test="${cart.count > 1}">
<p>You have ${cart.count} items in your cart.</p>
</c:if>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 17
How to code an if/else statement
<c:choose>
<c:when test="${cart.count == 0}">
<p>Your cart is empty.</p>
</c:when>
<c:when test="${cart.count == 1}">
<p>You have 1 item in your cart.</p>
</c:when>
<c:otherwise>
<p>You have ${cart.count} items in your cart.</p>
</c:otherwise>
</c:choose>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 18
The if and choose tags
Use the if tag to perform conditional processing that’s similar to
an if statement in Java.
Use the choose tag to perform conditional processing similar to an
if/else statement in Java. To do that, code multiple when tags and
a single otherwise tag within the choose tag.
If necessary, nest one if or choose tag within another.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 19
A link that doesn’t use the url tag
<a href="cart">Continue Shopping</a>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 20
A browser with the session ID encoded in its URL
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 21
The url tag
You can use the JSTL url tag to encode URLs within your web
application that are relative to the application’s root directory. As
a result, it can prevent your code from breaking if the application
context changes.
By default, the url tag automatically rewrites the URL to include
the session ID whenever necessary. This can lead to session
hijacking. To prevent this, add a tracking-mode element to the
web.xml file to specify the application should only use cookies
(not URL encoding) for tracking.
Use the JSTL param tag if you want to automatically encode
unsafe characters such as spaces with special characters such as
plus signs.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 22
Other tags in the JSTL core library
Tag name Description
set Sets the value of an attribute in a scope.
remove Removes an attribute from a scope.
catch Catches any exception that occurs in its body and
optionally creates an EL variable that refers to the
Throwable object for the exception.
redirect Redirects the client browser to a new URL.
param Adds a parameter to the parent tag.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 23
How to set a value in an attribute
<c:set var="message" scope="session" value="Test message" />
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 24
How to catch an exception
<c:catch var="e">
<% // this scriptlet statement throws an exception
int i = 1/0;
%>
<p>Result: <c:out value="${i}" /></p>
</c:catch>
<c:if test="${e != null}">
<p>An exception occurred. Message: ${e.message}</p>
</c:if>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 25
The Index page
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 26
The Cart page
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 27
The Product class
package murach.business;
import java.io.Serializable;
import java.text.NumberFormat;
public Product() {
code = "";
description = "";
price = 0;
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 28
The Product class (contined)
public void setDescription(String description) {
this.description = description;
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 29
The LineItem class
package murach.business;
import java.io.Serializable;
import java.text.NumberFormat;
public LineItem() {}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 30
The LineItem class (continued)
public void setQuantity(int quantity) {
this.quantity = quantity;
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 31
The Cart class
package murach.business;
import java.io.Serializable;
import java.util.ArrayList;
public Cart() {
items = new ArrayList<LineItem>();
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 32
The Cart class (continued)
public void addItem(LineItem item) {
String code = item.getProduct().getCode();
int quantity = item.getQuantity();
for (int i = 0; i < items.size(); i++) {
LineItem lineItem = items.get(i);
if (lineItem.getProduct().getCode().equals(code)) {
lineItem.setQuantity(quantity);
return;
}
}
items.add(item);
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 33
The index.jsp file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Murach's Java Servlets and JSP</title>
<link rel="stylesheet" href="styles/main.css" type="text/css"/>
</head>
<body>
<h1>CD list</h1>
<table>
<tr>
<th>Description</th>
<th class="right">Price</th>
<th> </th>
</tr>
<tr>
<td>86 (the band) - True Life Songs and Pictures</td>
<td class="right">$14.95</td>
<td><form action="cart" method="post">
<input type="hidden" name="productCode" value="8601">
<input type="submit" value="Add To Cart">
</form></td>
</tr>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 34
The index.jsp file (continued)
<tr>
<td>Paddlefoot - The first CD</td>
<td class="right">$12.95</td>
<td><form action="cart" method="post">
<input type="hidden" name="productCode" value="pf01">
<input type="submit" value="Add To Cart">
</form></td>
</tr>
<tr>
<td>Paddlefoot - The second CD</td>
<td class="right">$14.95</td>
<td><form action="cart" method="post">
<input type="hidden" name="productCode" value="pf02">
<input type="submit" value="Add To Cart">
</form></td>
</tr>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 35
The index.jsp file (continued)
<tr>
<td>Joe Rut - Genuine Wood Grained Finish</td>
<td class="right">$14.95</td>
<td><form action="cart" method="post">
<input type="hidden" name="productCode" value="jr01">
<input type="submit" value="Add To Cart">
</form></td>
</tr>
</table>
</body>
</html>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 36
The CartServlet class
package murach.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import murach.data.*;
import murach.business.*;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ServletContext sc = getServletContext();
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 37
The CartServlet class (continued)
// perform action and set URL to appropriate page
String url = "/index.jsp";
if (action.equals("shop")) {
url = "/index.jsp"; // the "index" page
}
else if (action.equals("cart")) {
String productCode = request.getParameter("productCode");
String quantityString = request.getParameter("quantity");
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 38
The CartServlet class (continued)
//if the user enters a negative or invalid quantity,
//the quantity is automatically reset to 1.
int quantity;
try {
quantity = Integer.parseInt(quantityString);
if (quantity < 0) {
quantity = 1;
}
} catch (NumberFormatException nfe) {
quantity = 1;
}
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 39
The CartServlet class (continued)
session.setAttribute("cart", cart);
url = "/cart.jsp";
}
else if (action.equals("checkout")) {
url = "/checkout.jsp";
}
sc.getRequestDispatcher(url)
.forward(request, response);
}
}
Note
In the web.xml file, the CartServlet class is mapped to the “/cart”
URL.
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 40
The cart.jsp file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Murach's Java Servlets and JSP</title>
<link rel="stylesheet" href="styles/main.css" type="text/css"/>
</head>
<body>
<h1>Your cart</h1>
<table>
<tr>
<th>Quantity</th>
<th>Description</th>
<th>Price</th>
<th>Amount</th>
<th></th>
</tr>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 41
The cart.jsp file (continued)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="item" items="${cart.items}">
<tr>
<td>
<form action="" method="post">
<input type="hidden" name="productCode"
value="<c:out value='${item.product.code}'/>">
<input type=text name="quantity"
value="<c:out value='${item.quantity}'/>" id="quantity">
<input type="submit" value="Update">
</form>
</td>
<td><c:out value='${item.product.description}'/></td>
<td>${item.product.priceCurrencyFormat}</td>
<td>${item.totalCurrencyFormat}</td>
<td>
<form action="" method="post">
<input type="hidden" name="productCode"
value="<c:out value='${item.product.code}'/>">
<input type="hidden" name="quantity" value="0">
<input type="submit" value="Remove Item">
</form>
</td>
</tr>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 42
The cart.jsp file (continued)
</c:forEach>
</table>
</body>
</html>
Murach's Java Servlets/JSP (3rd Ed.), C9 © 2014, Mike Murach & Associates, Inc. Slide 43