Ch23

advertisement
Chapter 23
The Cart application
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 1
A Product page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 2
The Quick Order page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 3
The Cart page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 4
The User page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 5
The Invoice page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 6
The Credit Card page
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 7
The structure of the Cart application
music.cart package
quick_order.jsp
DisplayQuickOrderServlet
cart.jsp
DisplayCartServlet
user.jsp
CheckUserServlet
SSL
ProcessUserServlet
invoice.jsp
DisplayInvoiceServlet
credit_card.jsp
CompleteOrderServlet
complete.jsp
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 8
The DisplayQuickOrderServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.ArrayList;
import music.business.*;
import music.data.*;
public class DisplayQuickOrderServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 9
The DisplayQuickOrderServlet class (cont.)
// if list of products doesn't exist, initialize it,
// and store it for the remainder of the session
if (session.getAttribute("products") == null)
{
ArrayList<Product> products =
ProductDB.selectProducts();
session.setAttribute("products", products);
}
// forward to the Quick Order page
String url = "/cart/quick_order.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 10
The code for the Quick Order page
<jsp:include page="/includes/header.html" />
<jsp:include page="/includes/column_left_order.jsp" />
<!-- begin middle column -->
<td width="570" valign="top" colspan="2">
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Quick order an album</h1>
<table cellpadding="5" border="0">
<tr valign="bottom">
<th align="left">Description</th>
<th align="left">Price</th>
<th align="left"> </th>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 11
The code for the Quick Order page (cont.)
<c:forEach var="product" items="${products}">
<tr valign="top">
<td>
<a href="
<c:url value='/catalog/displayProduct?productCode=
${product.code}'/>">
${product.description}
</a>
</td>
<td>${product.priceCurrencyFormat}</td>
<td>
<a href="
<c:url value='/cart/displayCart?productCode=
${product.code}'/>">
Add To Cart
</a></td>
</tr>
</c:forEach>
</table>
</td>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 12
The code for the Quick Order page (cont.)
<!-- end middle column -->
<jsp:include page="/includes/footer.jsp" />
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 13
The links from a Product page that call the
DisplayCartServlet class
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<a href="<c:url value=
'/cart/displayCart?productCode=${product.code}'/>">
<img src="/musicStore/images/addtocart.gif"
width="113" height="47">
</a><br><br>
<a href="<c:url value='/cart/displayCart'/>">
<img src="/musicStore/images/showcart.gif" width="113"
height="47">
</a><br><br>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 14
The DisplayCartServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import music.business.*;
import music.data.*;
public class DisplayCartServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String quantityString =
request.getParameter("quantity");
String productCode =
request.getParameter("productCode");
String removeButtonValue =
request.getParameter("removeButton");
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 15
The DisplayCartServlet class (cont.)
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null)
{
cart = new Cart();
session.setAttribute("cart", cart);
}
// If the user enters a negative or invalid number
// in the Update text box, the quantity is
// automatically reset to 1.
int quantity = 1;
try
{
quantity = Integer.parseInt(quantityString);
if (quantity < 0)
quantity = 1;
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 16
The DisplayCartServlet class (cont.)
catch(NumberFormatException nfe)
{
quantity = 1;
}
// If the user clicks the Remove button
if (removeButtonValue != null)
{
quantity = 0;
}
// Get product from product code
Product product =
ProductDB.selectProduct(productCode);
session.setAttribute("product", product);
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 17
The DisplayCartServlet class (cont.)
// If product exists, add or remove from cart
if (product != null)
{
LineItem lineItem = new LineItem();
lineItem.setProduct(product);
lineItem.setQuantity(quantity);
if (quantity > 0)
cart.addItem(lineItem);
else
cart.removeItem(lineItem);
}
session.setAttribute("cart", cart);
// If no items exist in cart, forward to the Quick
// Order page.Otherwise, forward to the Cart page.
String url = "";
if (cart.getItems().size() <= 0)
{
url = "/cart/displayQuickOrder";
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 18
The DisplayCartServlet class (cont.)
else
{
url = "/cart/cart.jsp";
}
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doPost(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 19
The cart.jsp file
<jsp:include page="/includes/header.html" />
<jsp:include page="/includes/column_left_all.jsp" />
<!-- begin middle column -->
<td>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Your cart</h1>
<form action="<c:url value='/cart/displayCart' />"
method="post">
<table cellspacing="5" border="0">
<tr>
<th align="left">Qty</th>
<th align="left">Description</th>
<th align="left">Price</th>
<th align="left">Amount</th>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 20
The cart.jsp file (cont.)
<c:forEach var="item" items="${cart.items}">
<tr valign="top">
<td>
<input type="hidden" name="productCode"
value="${item.product.code}">
<input type="text" size="2" name="quantity"
value="${item.quantity}">
<input type="submit" value="Update">
</td>
<td>${item.product.description}</td>
<td>${item.product.priceCurrencyFormat}</td>
<td>${item.totalCurrencyFormat}</td>
<td><input type="submit" name="removeButton"
value="Remove"></td>
</tr>
</c:forEach>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 21
The cart.jsp file (cont.)
<tr>
<td colspan="3">
<p><b>To change the quantity for an item</b>, enter
the new quantity and click on the Update
button.</p>
<p><b>To remove an item</b>, click on the Remove
button.</p>
</td>
</tr>
</table>
</form>
<form action="<c:url value='/cart/displayQuickOrder' />"
method="post">
<input type="submit" value="Continue Shopping">
</form>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 22
The cart.jsp file (cont.)
<form action=
"<c:url value=
'https://localhost:8443/musicStore/cart/checkUser' />"
method="post">
<input type="submit" value="Checkout">
</form>
<!-- end middle column -->
<jsp:include page="/includes/footer.jsp" />
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 23
The CheckUserServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import music.business.*;
import music.data.*;
import music.util.*;
public class CheckUserServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
String url = "/cart/user.jsp";
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 24
The CheckUserServlet class (cont.)
// if the User object exists with address1,
// skip User page
if (user != null && !user.getAddress1().equals("") )
{
url = "/cart/displayInvoice";
}
// otherwise, check the email cookie
else
{
Cookie[] cookies = request.getCookies();
String emailAddress =
CookieUtil.getCookieValue(
cookies, "emailCookie");
if (emailAddress.equals(""))
{
user = new User();
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 25
The CheckUserServlet class (cont.)
else
{
user = UserDB.selectUser(emailAddress);
if (user != null &&
!user.getAddress1().equals("") )
url = "/cart/displayInvoice";
}
}
session.setAttribute("user", user);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 26
The user.jsp file
<jsp:include page="/includes/header.html" />
<jsp:include page="/includes/column_left_all_absolute.jsp" />
<!-- begin middle column -->
<td>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Enter your name and contact information</h1>
<form action="<c:url value='/cart/processUser' />"
method=post>
<table border="0" cellpadding="5">
<tr>
<td></td>
<td align=left>Required <font color=red>*</font></td>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 27
The user.jsp file (cont.)
<tr>
<td align=right>First Name</td>
<td><input type="text" name="firstName" size="20"
maxlength=20 value="${user.firstName}">
<font color=red>*</font></td>
</tr>
<tr>
<td align=right>Last Name</td>
<td><input type=text name="lastName" size=20
value="${user.lastName}">
<font color=red>*</font></td>
</tr>
.
.
<tr>
<td align=right>Country</td>
<td><input type=text name="country" size=20
value="${user.country}">
<font color=red>*</font></td>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 28
The user.jsp file (cont.)
<tr>
<td align=right> </td>
<td><input type="button" value="Continue"
onClick="validate(this.form)"></td>
</tr>
</table>
</form>
</td>
<!-- end middle column -->
<jsp:include page="/includes/footer.jsp" />
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 29
The ProcessUserServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import music.business.*;
public class ProcessUserServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String firstName =
request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String companyName =
request.getParameter("companyName");
String emailAddress =
request.getParameter("emailAddress");
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 30
The ProcessUserServlet class (cont.)
String
String
String
String
String
String
address1 = request.getParameter("address1");
address2 = request.getParameter("address2");
city = request.getParameter("city");
state = request.getParameter("state");
zip = request.getParameter("zip");
country = request.getParameter("country");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
user.setCompanyName(companyName);
user.setAddress1(address1);
user.setAddress2(address2);
user.setCity(city);
user.setState(state);
user.setZip(zip);
user.setCountry(country);
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 31
The ProcessUserServlet class (cont.)
session.setAttribute("user", user);
String url = "/cart/displayInvoice";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 32
The DisplayInvoiceServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import music.business.*;
public class DisplayInvoiceServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
Cart cart = (Cart) session.getAttribute("cart");
java.util.Date today = new java.util.Date();
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 33
The DisplayInvoiceServlet class (cont.)
Invoice invoice = new Invoice();
invoice.setUser(user);
invoice.setInvoiceDate(today);
invoice.setLineItems(cart.getItems());
session.setAttribute("invoice", invoice);
String url = "/cart/invoice.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 34
The invoice.jsp file
<jsp:include page="/includes/header.html" />
<jsp:include page=
"/includes/column_left_all_absolute.jsp" />
<!-- begin middle column -->
<td>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Your invoice</h1>
<table border="0" cellspacing="5">
<tr><td><b>Date:</b></td>
<td width="400">
${invoice.invoiceDateDefaultFormat}</td>
<td></td>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 35
The invoice.jsp file (cont.)
<tr valign="top">
<td><b>Ship To:</b></td>
<td>${user.addressHTMLFormat}</td>
<td></td>
</tr>
<tr><td colspan="3"><hr></td></tr>
<tr><td><b>Qty</b></td>
<td><b>Description</b></td>
<td><b>Price</b></td>
</tr>
<c:forEach var="item" items="${invoice.lineItems}">
<tr>
<td><p>${item.quantity}</td>
<td><p>${item.product.description}</td>
<td><p>${item.totalCurrencyFormat}</td>
</tr>
</c:forEach>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 36
The invoice.jsp file (cont.)
<tr>
<td><b>Total:</b></td>
<td></td>
<td>${invoice.invoiceTotalCurrencyFormat}</td>
</tr>
</table>
<form action="<c:url value='/cart/user.jsp' />"
method="post">
<input type="submit" value="Edit Address">
</form>
<form action="<c:url value='/cart/credit_card.jsp' />"
method="post">
<input type="submit" value="Continue">
</form>
</td>
<!-- end middle column -->
<jsp:include page="/includes/footer.jsp" />
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 37
The creditcard.jsp file
<td>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Enter your credit card information</h1>
<form action="<c:url value='/cart/completeOrder' />"
method="post">
<table border="0" cellpadding="5">
<tr>
<td align="right"><p>Credit card type</td>
<td><select name="creditCardType" size="1">
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="AmEx">American Express</option>
</select>
</td>
</tr>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 38
The creditcard.jsp file (cont.)
<tr>
<td align="right">Card number</td>
<td><input type="text" size="20"
name="creditCardNumber"
maxlength="25"></td>
</tr>
<tr>
<td align="right"><p>Expiration date (mm/yyyy)</td>
<td><select name="creditCardExpirationMonth">
<option value="01">01
<option value="02">02
<option value="03">03
<option value="04">04
<option value="05">05
<option value="06">06
<option value="07">07
<option value="08">08
<option value="09">09
<option value="10">10
<option value="11">11
<option value="12">12
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 39
The creditcard.jsp file (cont.)
</select>
/
<select name="creditCardExpirationYear">
<c:forEach var="year"
items="${creditCardYears}">
<option value="${year}">${year}
</c:forEach>
</select>
</td>
</tr>
<tr>
<td></td>
<td align="left">
<input type="submit" value="Submit Order"></td>
</tr>
</table>
</form>
</td>
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 40
The CompleteOrderServlet class
package music.cart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import javax.mail.*;
import music.business.*;
import music.data.*;
import music.util.*;
public class CompleteOrderServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 41
The CompleteOrderServlet class (cont.)
Invoice invoice =
(Invoice)session.getAttribute("invoice");
String creditCardType =
request.getParameter("creditCardType");
String creditCardNumber =
request.getParameter("creditCardNumber");
String creditCardExpMonth = request.getParameter(
"creditCardExpirationMonth");
String creditCardExpYear = request.getParameter(
"creditCardExpirationYear");
user.setCreditCardType(creditCardType);
user.setCreditCardNumber(creditCardNumber);
user.setCreditCardExpirationDate(creditCardExpMonth
+ "/" + creditCardExpYear);
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 42
The CompleteOrderServlet class (cont.)
// If a record for the User object exists, update it
if (UserDB.emailExists(user.getEmailAddress()))
{
UserDB.update(user);
}
// Otherwise, write a new record for the User object
else
{
UserDB.insert(user);
}
// Write a new invoice record
InvoiceDB.insert(invoice);
// Set the emailCookie in the user's browser.
Cookie emailCookie = new Cookie("emailCookie",
user.getEmailAddress());
emailCookie.setMaxAge(60*24*365*2*60);
emailCookie.setPath("/");
response.addCookie(emailCookie);
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 43
The CompleteOrderServlet class (cont.)
// Remove all items from the user's cart
Cart cart = (Cart) session.getAttribute("cart");
cart.setItems(new ArrayList<LineItem>());
// Send an email to the user to confirm the order.
String to = user.getEmailAddress();
String from = "confirmation@freshcornrecords.com";
String subject = "Order Confirmation";
String body =
"Dear " + user.getFirstName() + ",\n\n" +
"Thanks for ordering from us. " +
"You should receive your order in " +
"3-5 business days. " +
"Please contact us if you have any questions.\n" +
"Have a great day and thanks again!\n\n" +
"Joe King\n" +
"Fresh Corn Records";
boolean isBodyHTML = false;
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 44
The CompleteOrderServlet class (cont.)
try
{
MailUtil.sendMail(
to, from, subject, body, isBodyHTML);
}
catch(MessagingException e)
{
this.log(
"Unable to send email. \n" +
"You may need to configure your system as " +
"described in chapter 15. \n" +
"Here is the email you tried to send: \n" +
"=====================================\n" +
"TO: " + to + "\n" +
"FROM: " + from + "\n" +
"SUBJECT: " + subject + "\n" +
"\n" +
body + "\n\n");
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 45
The CompleteOrderServlet class (cont.)
String url = "/cart/complete.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
Murach’s Java Servlets/JSP (2nd Ed.), C23
© 2008, Mike Murach & Associates, Inc.
Slide 46
Download