// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());
// If the user has no cart, create a new one
if (cart == null) {
cart = new ShoppingCart();
session.putValue(session.getId(), cart);
}
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the data of the response
out.println("<html>" +
"<head><title> Book Catalog </title></head>" +
"<body bgcolor=\"#ffffff\">" +
"<center>" +
"<hr> <br> " +
"<h1>" +
"<font size=\"+3\" color=\"red\">Duke's </font>" +
"<font size=\"+3\" color=\"purple\">Bookstore</font>" +
"</h1>" +
"</center>" +
"<br> <hr> <br> ");
//Data on the books are from the database servlet
BookDBServlet database = (BookDBServlet)
getServletConfig().getServletContext().getServlet("bookdb");
// Additions to the shopping cart
String bookToAdd = request.getParameter("Buy");
if (bookToAdd != null) {
BookDetails book = database.getBookDetails(bookToAdd);
cart.add(bookToAdd, book);
out.println("<p><h3>" +
"<font color=\"#ff0000\">" +
"You just added <i>" + book.getTitle() + "</i> "+
"to your shopping cart</font></h3>");
}
//Give the option of checking cart or checking out if cart not empty
if (cart.getNumberOfItems() > 0) {
out.println("<table><tr>" +
"<th align=\"left\"><a href=\"" +
response.encodeUrl("/servlet/showcart") +
"\"> Check Shopping Cart</a></th>" +
"<th> </th>" +
"<th align=\"right\"><a href=\"" +
response.encodeUrl("/servlet/cashier") +
"\"> Buy your Books</a></th>" +
"</tr></table");
}
// Always prompt the user to buy more -- get and show the catalog
out.println("<br> " +
"<h3>Please choose from our selections</h3>" +
"<center> <table>");
BookDetails[] books = database.getBooksSortedByTitle();
int numBooks = database.getNumberOfBooks();
for(int i=0; i < numBooks; i++) {
String bookId = books[i].getBookId();
//Print out info on each book in its own two rows
out.println("<tr>" +
"<td bgcolor=\"#ffffaa\">" +
"<a href=\"" +
response.encodeUrl("/servlet/bookdetails?bookId=" +
bookId) +
"\"> <strong>" + books[i].getTitle() +
" </strong></a></td>" +
"<td bgcolor=\"#ffffaa\" rowspan=2>" +
"$" + books[i].getPrice() +
" </td>" +
"<td bgcolor=\"#ffffaa\" rowspan=2>" +
"<a href=\"" +
response.encodeUrl("/servlet/catalog?Buy=" + bookId)
+ "\"> Add to Cart </a></td></tr>" +
"<tr>" +
"<td bgcolor=\"#ffffff\">" +
" by <em> " + books[i].getFirstName() +
" " + books[i].getSurname() + "</em></td></tr>");
}
out.println("</table></center></body></html>");
out.close();