
Before you begin, you need to install the following software on your
computer.
In this exercise, you are going to create
a new JDBC resource and then create
database tables that will be used by the Bookstore sample application.








Figure-0.10: Start Sun Java System Application Server

Figure-0.11: View Admin Console of the Sun Java System App Server

Figure-0.12: Log in to the admin console

Figure-0.13: Create a new JDBC Resource

Figure-0.14: Configure new JDBC Resource
8. Observe that jdbc/BookDB is now added.

Figure-0.15: Set the DatabaseName to sample and set the
connectionAttributes to create=false

Figure-0.30: Start Java DB Server

Figure-0.50: Connect to a database
2. If Connect dialog appears, for the
password field, type in app.
(Figure-0.51 below)

Figure-0.51: Provide database admin user name and password
3. Get books.sql
script.

Figure-0.52: Open file

Figure-0.53: Select books.sql

Figure-0.54: Select Execute Command
| CREATE TABLE BOOKS (id VARCHAR(8), surname VARCHAR(24), first_name VARCHAR(24), title VARCHAR(96), price FLOAT, onSale SMALLINT, calendar_year INT, description VARCHAR(30), inventory INT); INSERT INTO BOOKS VALUES('201', 'Duke', '', 'My Early Years: Growing up on *7', 30.75, 0, 1995, 'What a cool book.', 20); INSERT INTO BOOKS VALUES('202', 'Jeeves', '', 'Web Servers for Fun and Profit', 40.75, 1, 2000, 'What a cool book.', 20); INSERT INTO BOOKS VALUES('203', 'Masterson', 'Webster', 'Web Components for Web Developers', 27.75, 0, 2000, 'What a cool book.', 20); INSERT INTO BOOKS VALUES('205', 'Novation', 'Kevin', 'From Oak to Java: The Revolution of a Language', 10.75, 1, 1998, 'What a cool book.', 20); INSERT INTO BOOKS VALUES('206', 'Gosling', 'James', 'Java Intermediate Bytecodes', 30.95, 1, 2000, 'What a cool book.', 20); INSERT INTO BOOKS VALUES('207', 'Thrilled', 'Ben', 'The Green Project: Programming for Consumer Devices', 30.00, 1, 1998, 'What a cool book', 20); INSERT INTO BOOKS VALUES('208', 'Tru', 'Itzal', 'Duke: A Biography of the Java Evangelist', 45.00, 0, 2001, 'What a cool book.', 20); |

Figure-0.56: SQL Command is created




In this exercise, you are going to build
and run "bookstore1" sample
application, which uses only Servlets.
0. Start NetBeans IDE (if it has not been
started already)
1. Open bookstore1
NetBeans project (that is provided as part of hands-on lab zip file).
2 Build and run bookstore1 project.

Figure-1.12: Running bookstore1 project
Trouble-shooting-1: If you see the following
error condition (Figure-1.13 in the browser and Figure-1.14 in the Sun
Java System App server log file), it is likely because the database has
not been started.

Figure-1.13: Error condition

Figure-1.14: Error condition
Solution: Start the Derby database server (Java DB Server) by selcting Tools->Java DB Database->Start Java DB Server. Right click bookstore1 project and select Clean and Build, then Run Project.
2. Click Duke:
A Biography of the Java Evangelist or any other book on the
page. (Figure-1.13 below)

Figure-1.13: Select a book
3. Select Add to Cart. (Figure-1.14 below)

Figure-1.14: Add to Cart
4. Select Buy Your Books. (Figure-1.15 below)

Figure-1.15: Select Buy Your Books.
5. Click Submit
Information.

Figure-1.16: Click Submit Information
| package listeners; import database.BookDBAO; import javax.servlet.*; import util.Counter; // Event handler class for handling application scope events public final class ContextListener implements ServletContextListener { private ServletContext context = null; // This method gets called when the application is deployed public void contextInitialized(ServletContextEvent event) { context = event.getServletContext(); // Create BookDBAO object and save it as an attribute to // ServletContext scope object. try { BookDBAO bookDB = new BookDBAO(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.println("Couldn't create bookstore database bean: " + ex.getMessage()); } // Save hitCounter and orderCounter attributes in the // ServletContext scope object Counter counter = new Counter(); context.setAttribute("hitCounter", counter); counter = new Counter(); context.setAttribute("orderCounter", counter); } // This method gets called when the application is undeployed public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDBAO bookDB = (BookDBAO) context.getAttribute("bookDB"); if (bookDB != null) { bookDB.remove(); } context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); } } |
| <?xml version="1.0"
encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>bookstore1</display-name> <filter> <filter-name>OrderFilter</filter-name> <filter-class>filters.OrderFilter</filter-class> </filter> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>filters.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter-name>OrderFilter</filter-name> <servlet-name>ReceiptServlet</servlet-name> </filter-mapping> <filter-mapping> <filter-name>HitCounterFilter</filter-name> <servlet-name>BookStoreServlet</servlet-name> </filter-mapping> <listener> <listener-class>listeners.ContextListener</listener-class> </listener> ... </web-app> |
| package database; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; import exception.*; import cart.*; // The instance of BookDBAO gets created when the application // is deployed. It maintains the Connection object to the // database. The Connection object is created from DataSource // object, which is retrieved through JNDI. // For more information on DataSource, please see // http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.html. // // It also maintains list of books in the form of ArrayList. // // Study points: // - How DataSource object is retrieved through JNDI // - How Connection object is obtained through DataSource object public class BookDBAO { private ArrayList books; Connection con; private boolean conFree = true; public BookDBAO() throws Exception { try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/BookDB"); con = ds.getConnection(); } catch (Exception ex) { throw new Exception("Couldn't open connection to database: " + ex.getMessage()); } } public void remove() { try { con.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } protected synchronized Connection getConnection() { while (conFree == false) { try { wait(); } catch (InterruptedException e) { } } conFree = false; notify(); return con; } protected synchronized void releaseConnection() { while (conFree == true) { try { wait(); } catch (InterruptedException e) { } } conFree = true; notify(); } // Return the list of books. // // // Study points: // - How PreparedStatement is used for database operations // - How ResultSet object is used for returned values // public List getBooks() throws BooksNotFoundException { books = new ArrayList(); try { String selectStatement = "select * " + "from books"; getConnection(); PreparedStatement prepStmt = con.prepareStatement(selectStatement); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { BookDetails bd = new BookDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getFloat(5), rs.getBoolean(6), rs.getInt(7), rs.getString(8), rs.getInt(9)); if (rs.getInt(9) > 0) { books.add(bd); } } prepStmt.close(); } catch (SQLException ex) { throw new BooksNotFoundException(ex.getMessage()); } releaseConnection(); Collections.sort(books); return books; } // Get book details given a book id // public BookDetails getBookDetails(String bookId) throws BookNotFoundException { try { String selectStatement = "select * " + "from books where id = ? "; getConnection(); PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, bookId); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { BookDetails bd = new BookDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getFloat(5), rs.getBoolean(6), rs.getInt(7), rs.getString(8), rs.getInt(9)); prepStmt.close(); releaseConnection(); return bd; } else { prepStmt.close(); releaseConnection(); throw new BookNotFoundException("Couldn't find book: " + bookId); } } catch (SQLException ex) { releaseConnection(); throw new BookNotFoundException("Couldn't find book: " + bookId + " " + ex.getMessage()); } } // Buy books by calling buyBook() method for each book in the // shopping cart. // // Study points: // - How setAutoCommit() method of a Connection object is used // - How Connection object is retrieved and released // public void buyBooks(ShoppingCart cart) throws OrderException { Collection items = cart.getItems(); Iterator i = items.iterator(); try { getConnection(); con.setAutoCommit(false); while (i.hasNext()) { ShoppingCartItem sci = (ShoppingCartItem) i.next(); BookDetails bd = (BookDetails) sci.getItem(); String id = bd.getBookId(); int quantity = sci.getQuantity(); buyBook(id, quantity); } con.commit(); con.setAutoCommit(true); releaseConnection(); } catch (Exception ex) { try { con.rollback(); releaseConnection(); throw new OrderException("Transaction failed: " + ex.getMessage()); } catch (SQLException sqx) { releaseConnection(); throw new OrderException("Rollback failed: " + sqx.getMessage()); } } } // Buy a book - basically reducing the quantity of books in the database. // public void buyBook(String bookId, int quantity) throws OrderException { try { String selectStatement = "select * " + "from books where id = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, bookId); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { int inventory = rs.getInt(9); prepStmt.close(); if ((inventory - quantity) >= 0) { String updateStatement = "update books set inventory = inventory - ? where id = ?"; prepStmt = con.prepareStatement(updateStatement); prepStmt.setInt(1, quantity); prepStmt.setString(2, bookId); prepStmt.executeUpdate(); prepStmt.close(); } else { throw new OrderException("Not enough of " + bookId + " in stock to complete order."); } } } catch (Exception ex) { throw new OrderException("Couldn't purchase book: " + bookId + ex.getMessage()); } } } |
| package filters; import java.io.*; import java.sql.Timestamp; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import util.Counter; // Servlet filter class for updating hitcounter public final class HitCounterFilter implements Filter { private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy() { this.filterConfig = null; } // This method gets called everythime BookStoreServlet gets accessed. // See filter mapping of the web.xml file. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } HttpServletRequest hr = (HttpServletRequest) request; HttpSession session = hr.getSession(); ResourceBundle messages = (ResourceBundle) session.getAttribute("messages"); if (messages == null) { Locale locale = request.getLocale(); messages = ResourceBundle.getBundle("messages.BookstoreMessages", locale); session.setAttribute("messages", messages); } StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Counter counter = (Counter) filterConfig.getServletContext() .getAttribute("hitCounter"); writer.println(); writer.println( "======================================================="); writer.println("The number of hits is: " + counter.incCounter()); writer.println( "======================================================="); // Log the resulting string writer.flush(); System.out.println(sw.getBuffer().toString()); PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response); // Pass the request to the next filter in the chain. chain.doFilter(request, wrapper); CharArrayWriter caw = new CharArrayWriter(); caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>") - 1)); caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font></center>"); caw.write("\n</body></html>"); response.setContentLength(caw.toString() .getBytes().length); out.write(caw.toString()); out.close(); } public String toString() { if (filterConfig == null) { return ("HitCounterFilter()"); } StringBuffer sb = new StringBuffer("HitCounterFilter("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); } } |
| <?xml version="1.0"
encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>bookstore1</display-name> <filter> <filter-name>OrderFilter</filter-name> <filter-class>filters.OrderFilter</filter-class> </filter> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>filters.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter-name>OrderFilter</filter-name> <servlet-name>ReceiptServlet</servlet-name> </filter-mapping> <filter-mapping> <filter-name>HitCounterFilter</filter-name> <servlet-name>BookStoreServlet</servlet-name> </filter-mapping> <listener> <listener-class>listeners.ContextListener</listener-class> </listener> <servlet> <display-name>ShowCartServlet</display-name> <servlet-name>ShowCartServlet</servlet-name> <servlet-class>servlets.ShowCartServlet</servlet-class> </servlet> <servlet> <display-name>CatalogServlet</display-name> <servlet-name>CatalogServlet</servlet-name> <servlet-class>servlets.CatalogServlet</servlet-class> </servlet> <servlet> <display-name>BookStoreServlet</display-name> <servlet-name>BookStoreServlet</servlet-name> <servlet-class>servlets.BookStoreServlet</servlet-class> </servlet> <servlet> <display-name>CashierServlet</display-name> <servlet-name>CashierServlet</servlet-name> <servlet-class>servlets.CashierServlet</servlet-class> </servlet> <servlet> <display-name>BannerServlet</display-name> <servlet-name>BannerServlet</servlet-name> <servlet-class>servlets.BannerServlet</servlet-class> </servlet> <servlet> <display-name>BookDetailsServlet</display-name> <servlet-name>BookDetailsServlet</servlet-name> <servlet-class>servlets.BookDetailsServlet</servlet-class> </servlet> <servlet> <display-name>ReceiptServlet</display-name> <servlet-name>ReceiptServlet</servlet-name> <servlet-class>servlets.ReceiptServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowCartServlet</servlet-name> <url-pattern>/bookshowcart</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CatalogServlet</servlet-name> <url-pattern>/bookcatalog</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BookStoreServlet</servlet-name> <url-pattern>/bookstore</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CashierServlet</servlet-name> <url-pattern>/bookcashier</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BannerServlet</servlet-name> <url-pattern>/banner</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BookDetailsServlet</servlet-name> <url-pattern>/bookdetails</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ReceiptServlet</servlet-name> <url-pattern>/bookreceipt</url-pattern> </servlet-mapping> <error-page> <exception-type>exception.BookNotFoundException</exception-type> <location>/errorpage.html</location> </error-page> <error-page> <exception-type>javax.servlet.UnavailableException</exception-type> <location>/errorpage.html</location> </error-page> <error-page> <exception-type>exception.BooksNotFoundException</exception-type> <location>/errorpage.html</location> </error-page> <jsp-config/> <resource-ref> <res-ref-name>jdbc/BookDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> </web-app> |
| package servlets; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import database.*; import exception.*; /** * An HTTP Servlet that overrides the service method to return a * simple web page. */ public class BookStoreServlet extends HttpServlet { private BookDBAO bookDB; public void init() throws ServletException { bookDB = (BookDBAO) getServletContext() .getAttribute("bookDB"); if (bookDB == null) { throw new UnavailableException("Couldn't get database."); } } public void destroy() { bookDB = null; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get HttpSession scope object and retrieve ResourceBundle object. HttpSession session = request.getSession(); ResourceBundle messages = (ResourceBundle) session.getAttribute("messages"); // Use the browser's locale. if (messages == null) { Locale locale = request.getLocale(); messages = ResourceBundle.getBundle("messages.BookstoreMessages", locale); session.setAttribute("messages", messages); } // set content-type header before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the data of the response out.println("<html>" + "<head><title>Duke's Bookstore</title></head>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher("/banner"); if (dispatcher != null) { dispatcher.include(request, response); } // Get book detail of the book 203 and display. // Study how encodeURL() method is used for URL encoding. try { BookDetails bd = bookDB.getBookDetails("203"); //Left cell -- the "book of choice" out.println("<b>" + messages.getString("What") + "</b>" + "<p>" + "<blockquote>" + "<em><a href=\"" + response.encodeURL(request.getContextPath() + "/bookdetails?bookId=203") + "\">" + bd.getTitle() + "</a></em>" + messages.getString("Talk") + "</blockquote>"); //Right cell -- various navigation options out.println("<p><a href=\"" + response.encodeURL(request.getContextPath() + "/bookcatalog") + "\"><b>" + messages.getString("Start") + "</b></a></font><br>" + "<br> " + "<br> " + "<br> " + "</body>" + "</html>"); } catch (BookNotFoundException ex) { response.resetBuffer(); throw new ServletException(ex); } out.close(); } public String getServletInfo() { return "The BookStore servlet returns the main web page " + "for Duke's Bookstore."; } } |
In this exercise, you have built
and run "bookstore1" sample application. You have looked into how
an event listener is written and configured. You also have seen
two filters. You studied how servlets are used to write
bookstore1 sample application.
In this exercise, you are going to build
and run "bookstore2" sample
application, which uses only JSP pages.
1. Open bookstore2
NetBeans project (that is provided as part of hands-on lab zip
file).
2 Build and run bookstore2 project.
| <?xml version="1.0"
encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>bookstore2</display-name> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>messages.BookstoreMessages</param-value> </context-param> <listener> <listener-class>listeners.ContextListener</listener-class> </listener> <servlet> <display-name>Dispatcher</display-name> <servlet-name>Dispatcher</servlet-name> <servlet-class>dispatcher.Dispatcher</servlet-class> </servlet> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookstore</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookdetails</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookcatalog</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookshowcart</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookcashier</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/bookreceipt</url-pattern> </servlet-mapping> <jsp-config> <jsp-property-group> <display-name>bookstore2</display-name> <url-pattern>*.jsp</url-pattern> <el-ignored>false</el-ignored> <scripting-invalid>false</scripting-invalid> <is-xml>false</is-xml> <include-prelude>/template/prelude.jspf</include-prelude> <include-coda>/template/coda.jspf</include-coda> </jsp-property-group> </jsp-config> <resource-ref> <res-ref-name>jdbc/BookDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> </web-app> |
| package dispatcher; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import cart.ShoppingCart; import database.*; import exception.*; public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { String bookId = null; String clear = null; BookDetails book = null; BookDBAO bookDBAO = (BookDBAO) getServletContext() .getAttribute("bookDBAO"); HttpSession session = request.getSession(); // Retrieve ServletPath from the request object. String selectedScreen = request.getServletPath(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); // If cart attribute is not present in the HttpSession scope object, // create one and save it. if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } // Based on the ServletPath, extract request parameters if (selectedScreen.equals("/bookcatalog")) { bookId = request.getParameter("Add"); if (!bookId.equals("")) { try { book = bookDBAO.getBookDetails(bookId); cart.add(bookId, book); } catch (BookNotFoundException ex) { // not possible } } } else if (selectedScreen.equals("/bookshowcart")) { bookId = request.getParameter("Remove"); if (bookId != null) { cart.remove(bookId); } clear = request.getParameter("Clear"); if ((clear != null) && clear.equals("clear")) { cart.clear(); } } else if (selectedScreen.equals("/bookreceipt")) { // Update the inventory try { bookDBAO.buyBooks(cart); } catch (OrderException ex) { selectedScreen = "/bookordererror"; } } // Determine the destination jsp for forwarding String screen = selectedScreen + ".jsp"; // Perform the forwarding try { request.getRequestDispatcher(screen) .forward(request, response); } catch (Exception ex) { ex.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) { String screen = request.getServletPath() + ".jsp"; try { request.getRequestDispatcher(screen) .forward(request, response); } catch (Exception ex) { ex.printStackTrace(); } } } |
| <%-- Display localized string
of "What" --%> <p><b><fmt:message key="What"/></b></p> <%-- Create bookDB attribute in a page scope --%> <jsp:useBean id="bookDB" class="database.BookDB" scope="page" > <jsp:setProperty name="bookDB" property="database" value="${bookDBAO}" /> </jsp:useBean> <%-- Set the bookId property of the bookDB bean with value of "203" --%> <jsp:setProperty name="bookDB" property="bookId" value="203" /> <p> <%-- Retrieve the result of /bookdetails --%> <c:url var="url" value="/bookdetails" /> <blockquote><p><em><a href="${url}?bookId=203">${bookDB.bookDetails.title}</a></em>, <c:url var="url" value="/bookcatalog" /> <fmt:message key="Talk"/></blockquote> <p><b><a href="${url}?Add="><fmt:message key="Start"/></a></b> |
| <jsp:useBean id="bookDB"
class="database.BookDB" scope="page" > <jsp:setProperty name="bookDB" property="database" value="${bookDBAO}" /> </jsp:useBean> <c:if test="${!empty param.bookId}"> <c:set var="bid" value="${param.bookId}"/> <jsp:setProperty name="bookDB" property="bookId" value="${bid}" /> <c:set var="book" value="${bookDB.bookDetails}" /> <h2>${book.title}</h2> <fmt:message key="By"/> <em>${book.firstName} ${book.surname}</em> (${book.year})<br> <br> <h4><fmt:message key="Critics"/></h4> <blockquote>${book.description}</blockquote> <h4><fmt:message key="ItemPrice"/>: <fmt:formatNumber value="${book.price}" type="currency"/></h4> <c:url var="url" value="/bookcatalog" > <c:param name="Add" value="${bid}" /> </c:url> <p><strong><a href="${url}"><fmt:message key="CartAdd"/></a> </c:if> <c:url var="url" value="/bookcatalog" > <c:param name="Add" value="" /> </c:url> <a href="${url}"><fmt:message key="ContinueShopping"/></a></p></strong> |
In this exercise, you are going to build
and run "bookstore3" sample
application, which uses JSP pages and custom tags that are created
using tag files.
0. Start NetBeans IDE and select Project tab.
1. Open bookstore3
NetBeans project.
2 Build and run bookstore3 project.


| <%@ taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <%@ attribute name="bookDB" required="true" type="database.BookDB" %> <%@ attribute name="color" required="true" %> <%@ attribute name="normalPrice" fragment="true" %> <%@ attribute name="onSale" fragment="true" %> <%@ variable name-given="price" %> <%@ variable name-given="salePrice" %> <center> <table summary="layout"> <c:forEach var="book" begin="0" items="${bookDB.books}"> <tr> <c:set var="bookId" value="${book.bookId}" /> <td bgcolor="${color}"> <c:url var="url" value="/bookdetails" > <c:param name="bookId" value="${bookId}" /> </c:url> <a href="${url}"><strong>${book.title} </strong></a></td> <td bgcolor="${color}" rowspan=2> <c:set var="salePrice" value="${book.price * .85}" /> <c:set var="price" value="${book.price}" /> <c:choose> <c:when test="${book.onSale}" > <jsp:invoke fragment="onSale" /> </c:when> <c:otherwise> <jsp:invoke fragment="normalPrice" /> </c:otherwise> </c:choose> </td> <td bgcolor="${color}" rowspan=2> <c:url var="url" value="/bookcatalog" > <c:param name="Add" value="${bookId}" /> </c:url> <p><strong><a href="${url}"> <fmt:message key="CartAdd"/> </a></td></tr> <tr> <td bgcolor="#ffffff"> <fmt:message key="By"/> <em>${book.firstName} ${book.surname}</em></td></tr> </c:forEach> </table> </center> |
| <%@ taglib prefix="sc"
tagdir="/WEB-INF/tags" %> <jsp:useBean id="bookDB" class="database.BookDB" scope="page" > <jsp:setProperty name="bookDB" property="database" value="${bookDBAO}" /> </jsp:useBean> <c:if test="${!empty param.Add}"> <c:set var="bid" value="${param.Add}"/> <jsp:setProperty name="bookDB" property="bookId" value="${bid}" /> <c:set var="addedBook" value="${bookDB.bookDetails}" /> <p><h3><font color="red" size="+2"> <fmt:message key="CartAdded1"/> <em>${addedBook.title}</em> <fmt:message key="CartAdded2"/></font></h3> </c:if> <c:if test="${sessionScope.cart.numberOfItems > 0}"> <c:url var="url" value="/bookshowcart" > <c:param name="Clear" value="0" /> <c:param name="Remove" value="0" /> </c:url> <p><strong><a href="${url}"><fmt:message key="CartCheck"/></a> <c:url var="url" value="/bookcashier" /> <a href="${url}"><fmt:message key="Buy"/></a></p></strong> </c:if> <br> <br> <h3><fmt:message key="Choose"/></h3> <sc:catalog bookDB ="${bookDB}" color="#cccccc"> <jsp:attribute name="normalPrice"> <fmt:formatNumber value="${price}" type="currency"/> </jsp:attribute> <jsp:attribute name="onSale"> <strike><fmt:formatNumber value="${price}" type="currency"/></strike><br/> <font color="red"><fmt:formatNumber value="${salePrice}" type="currency"/></font> </jsp:attribute> </sc:catalog> |
In this exercise, you are going to build
and run "bookstore4" sample
application, which uses JSP pages and JSTL in native format.
0. Start NetBeans IDE and select Project tab.
1. Open bookstore4
NetBeans project.
2 Build and run bookstore4 project.