

<%@ page import="java.util.*" %>
<%@ page import="MyLocales" %>
<%@ page contentType="text/html; charset=ISO-8859-5" %>
<html>
<head><title>Localized Dates</title></head>
<body bgcolor="white">
<jsp:useBean id="locales" scope="application" class="MyLocales"/>
<form name="localeForm" action="index.jsp" method="post">
<b>Locale:</b>
<select name=locale>
<%
Iterator i = locales.getLocaleNames().iterator();
String selectedLocale = request.getParameter("locale");
while (i.hasNext()) {
String locale = (String)i.next();
if (selectedLocale != null && selectedLocale.equals(locale) ) {
%>
<option selected><%=locale%></option>
<%
} else {
%>
<option><%=locale%></option>
<%
}
}
%>
</select>
<input type="submit" name="Submit" value="Get Date">
</form>
<p>
<jsp:include page="date.jsp" flush="true" />
</body>
</html>
<%@ page import="java.util.*" %>
<%@ page import="MyDate,MyLocales" %>
<html>
<body bgcolor="white">
<jsp:useBean id="date" class="MyDate"/>
<jsp:useBean id="locales" scope="application" class="MyLocales"/>
<%
Locale locale = locales.getLocale(request.getParameter("locale"));
if (locale != null) {
%>
<jsp:setProperty name="date" property="locale" value="<%=locale%>"/>
The date in <b><%=locale.getDisplayName()%></b> is <b><%=date.getDate()%></b>
<% } %>
</body>
</html>
import java.util.*;
import java.text.DateFormat;
public class MyLocales {
HashMap locales;
ArrayList localeNames;
DateFormat dateFormatter;
public MyLocales() {
locales = new HashMap();
localeNames = new ArrayList();
Locale list[] = DateFormat.getAvailableLocales();
for (int i = 0; i < list.length; i++) {
locales.put(list[i].getDisplayName(), list[i]);
localeNames.add(list[i].getDisplayName());
}
Collections.sort(localeNames);
}
public Collection getLocaleNames() {
return localeNames;
}
public Locale getLocale(String displayName) {
return (Locale)locales.get(displayName);
}
}
C:\... >ant data
Buildfile: build.xml
init:
data:
[mkdir] Created dir: C:\...\build\data
[copy] Copying 3 files to C:\...\build\data
[javac] Compiling 2 source files to C:\...\build\data
BUILD SUCCESSFUL
Total time: 11 seconds
| Funcionalidade | Páginas JSP |
| Entrar na livraria | bookstore.jsp |
| Criar o banner da livraria | banner.jsp |
| Examinar o catálogo | catalog.jsp |
| Adicionar um livro à cesta de compras | catalog.jsp bookdetails.jsp |
| Receber informação detalhada sobre um livro | bookdetails.jsp |
| Mostrar a cesta de compras | showcart.jsp |
| Remover um ou mais livros da cesta de compras | showcart.jsp |
| Comprar os livros presentes na cesta de compras | cashier.jsp |
| Receber uma confirmação de pedido | receipt.jsp |
C:\...>ant livrosjsp
Buildfile: build.xml
init:
web-ejb:
[mkdir] Created dir: C:\...\build\webejb
[javac] Compiling 6 source files to C:\...\build\webejb
livrosjsp:
[mkdir] Created dir: C:\...\build\livrosjsp
[copy] Copying 11 files to C:\...\build\livrosjsp
[javac] Compiling 8 source files to C:\...\build\livrosjsp
[war] Building war: C:\...\build\livrosjsp\livrosjsp.war
BUILD SUCCESSFUL
Total time: 11 seconds
<%@ page buffer="none|xxxkb" %>
<%@ page errorPage="file_name" %>
<%@ page errorPage="errorpage.jsp"%>
<%@ page isErrorPage="true" %>
<%--
Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
This software is the proprietary information of Sun Microsystems, Inc.
Use is subject to license terms.
--%>
<%@ page isErrorPage="true" %>
<%@ page import="java.util.*" %>
<%
ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");
if (messages == null) {
Locale locale=null;
String language = request.getParameter("language");
if (language != null) {
if (language.equals("English")) {
locale=new Locale("en", "");
} else {
locale=new Locale("pt", "");
}
} else
locale=new Locale("en", "");
messages = ResourceBundle.getBundle("BookStoreMessages", locale);
session.setAttribute("messages", messages);
}
%>
<html>
<head>
<title><%=messages.getString("ServerError")%></title>
</head>
<body bgcolor="white">
<h3>
<%=messages.getString("ServerError")%>
</h3>
<p>
<%= exception.getMessage() %>
</body>
</html>
<%@ include file="initdestroy.jsp" %>
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%@ page import="javax.ejb.*, javax.naming.*,
javax.rmi.PortableRemoteObject, java.rmi.RemoteException,
database.BookDB, database.BookDBEJB, database.BookDBEJBHome"
%>
<%!
private BookDBEJB bookDBEJB;
public void jspInit() {
bookDBEJB =
(BookDBEJB)getServletContext().getAttribute("bookDBEJB");
if (bookDBEJB == null) {
try {
InitialContext ic = new InitialContext();
Object objRef = ic.lookup("java:comp/env/ejb/BookDBEJB");
BookDBEJBHome home = (BookDBEJBHome)PortableRemoteObject.narrow(objRef,
database.BookDBEJBHome.class);
bookDBEJB = home.create();
getServletContext().setAttribute("bookDBEJB", bookDBEJB);
} catch (RemoteException ex) {
System.out.println("Couldn't create database bean." + ex.getMessage());
} catch (CreateException ex) {
System.out.println("Couldn't create database bean." + ex.getMessage());
} catch (NamingException ex) {
System.out.println("Unable to lookup home: "+ "java:comp/env/ejb/BookDBEJB."+ ex.getMessage());
}
}
}
public void jspDestroy() {
bookDBEJB = null;
}
%>
<%@ page contentType="text/vnd.wap.wml"%>
| Variável | Classe | Descrição |
| application | javax.servlet.ServletContext | O contexto do servlet da página JSP e de qualquer Web Component contidos na mesma aplicação |
| config | javax.servlet.ServletConfig | Informação de inicialização para o servlet da página JSP |
| exception | java.lang.Throwable | Acessível apenas a partir de uma página de erro |
| out | javax.servlet.jsp.JspWriter | O stream de saída |
| page | java.lang.Object | A instância do servlet da página JSP processando o pedido atual. Raramente usado por autores de páginas JSP |
| pageContext | javax.servlet.jsp.PageContext | O contexto de uma página JSP. Provê uma API única para gerenciar atributos com escopo. Esta API é muito usada ao implementar "tag handlers" (ver em outro capítulo) |
| request | subtipo de javax.servlet.ServletRequest | O pedido gatilhando a execução da página JSP |
| response | subtipo de javax.servlet.ServletResponse | A resposta retornada ao cliente. Raramente usado por autores de páginas JSP |
| session | javax.servlet.http.HttpSession | O objeto de sessão com o cliente |
<%@ page isThreadSafe="true|false" %>
<%@ page language="linguagem de script" %>
<%@ page import="packagename.*, fully_qualified_classname" %>
<%@ page import="java.util.*, cart.*" %>
<%! declaração na linguagem de script %>
<%--
Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
This software is the proprietary information of Sun Microsystems, Inc.
Use is subject to license terms.
--%>
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%@ page import="javax.ejb.*, javax.naming.*,
javax.rmi.PortableRemoteObject, java.rmi.RemoteException,
database.BookDB, database.BookDBEJB, database.BookDBEJBHome"
%>
<%!
private BookDBEJB bookDBEJB;
public void jspInit() {
bookDBEJB =
(BookDBEJB)getServletContext().getAttribute("bookDBEJB");
if (bookDBEJB == null) {
try {
InitialContext ic = new InitialContext();
Object objRef = ic.lookup("java:comp/env/ejb/BookDBEJB");
BookDBEJBHome home = (BookDBEJBHome)PortableRemoteObject.narrow(objRef,
database.BookDBEJBHome.class);
bookDBEJB = home.create();
getServletContext().setAttribute("bookDBEJB", bookDBEJB);
} catch (RemoteException ex) {
System.out.println("Couldn't create database bean." + ex.getMessage());
} catch (CreateException ex) {
System.out.println("Couldn't create database bean." + ex.getMessage());
} catch (NamingException ex) {
System.out.println("Unable to lookup home: "+ "java:comp/env/ejb/BookDBEJB."+ ex.getMessage());
}
}
}
public void jspDestroy() {
bookDBEJB = null;
}
%>
<% comandos na linguagem de script %>
<%@ include file="initdestroy.jsp" %>
<%@ page import="java.util.*, cart.*" %>
<%
ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");
%>
<jsp:useBean id="bookDB" class="database.BookDB" scope="page" >
<jsp:setProperty name="bookDB" property="database" value="<%=bookDBEJB%>" />
</jsp:useBean>
<jsp:useBean id="cart" scope="session" class="cart.ShoppingCart"/>
<jsp:useBean id="currency" class="util.Currency" scope="session">
<jsp:setProperty name="currency" property="locale" value="<%=request.getLocale()%>"/>
</jsp:useBean>
<html>
<head><title><%=messages.getString("TitleShoppingCart")%></title></head>
<%@ include file="banner.jsp" %>
<%
String bookId = request.getParameter("Remove");
if (bookId != null) {
cart.remove(bookId);
bookDB.setBookId(bookId);
BookDetails book = bookDB.getBookDetails();
%>
<font color="red" size="+2"><%=messages.getString("CartRemoved")%><em><%=book.getTitle()%>
</em>
<br> <br>
</font>
<%
}
if (request.getParameter("Clear") != null) {
cart.clear();
%>
<font color="red" size="+2"><strong>
<%=messages.getString("CartCleared")%>
</strong><br> <br></font>
<%
}
// Print a summary of the shopping cart
int num = cart.getNumberOfItems();
if (num > 0) {
%>
<font size="+2"><%=messages.getString("CartContents")%><%=num%> <%=(num==1 ? messages.getString("CartItem") : messages.getString("CartItems"))%>
</font><br>
<table>
<tr>
<th align=left><%=messages.getString("ItemQuantity")%></TH>
<th align=left><%=messages.getString("ItemTitle")%></TH>
<th align=left><%=messages.getString("ItemPrice")%></TH>
</tr>
<%
Iterator i = cart.getItems().iterator();
while (i.hasNext()) {
ShoppingCartItem item = (ShoppingCartItem)i.next();
BookDetails book = (BookDetails)item.getItem();
%>
<tr>
<td align="right" bgcolor="#ffffff">
<%=item.getQuantity()%>
</td>
<td bgcolor="#ffffaa">
<strong><a href="<%=request.getContextPath()%>/bookdetails?bookId=<%=book.getBookId()%>">
<%=book.getTitle()%></a></strong>
</td>
<td bgcolor="#ffffaa" align="right">
<jsp:setProperty name="currency" property="amount" value="<%=book.getPrice()%>"/>
<jsp:getProperty name="currency" property="format"/> </td>
<td bgcolor="#ffffaa">
<strong>
<a href="<%=request.getContextPath()%>/showcart?Remove=<%=book.getBookId()%>"><%=messages.getString("RemoveItem")%></a></strong>
</td></tr>
<%
// End of while
}
%>
<tr><td colspan="5" bgcolor="#ffffff">
<br></td></tr>
<tr>
<td colspan="2" align="right" "bgcolor="#ffffff">
<%=messages.getString("Subtotal")%></td>
<td bgcolor="#ffffaa" align="right">
<jsp:setProperty name="currency" property="amount" value="<%=cart.getTotal()%>"/>
<jsp:getProperty name="currency" property="format"/>
</td>
</td><td><br></td></tr></table>
<p> <p>
<strong><a href="<%=request.getContextPath()%>/catalog"><%=messages.getString("ContinueShopping")%></a>
<a href="<%=request.getContextPath()%>/cashier"><%=messages.getString("Checkout")%></a>
<a href="<%=request.getContextPath()%>/showcart?Clear=clear"><%=messages.getString("ClearCart")%></a></strong>
<%
} else {
%>
<font size="+2"><%=messages.getString("CartEmpty")%></font>
<br> <br>
<center><a href="<%=request.getContextPath()%>/catalog"><%=messages.getString("Catalog")%></a> </center>
<%
// End of if
}
%>
</body>
</html>
<%= expressão na linguagem de script %>
<%@ include file="initdestroy.jsp" %> // ... <%@ include file="banner.jsp" %>
<jsp:include page="date.jsp"/>
<jsp:forward page="/main.jsp" />
<jsp:include page="..." > <jsp:param name=”param1” value="value1"/> </jsp:include>
livros programa