Servlet Database Access
Servlet Database Access : Data that is shared between Web components and is persistent between invocations of a J2EE application is usually maintained by a database. Web components use the JDBC 2.0 API to access relational databases. The data for the bookstore application is maintained in a database and accessed through the helper class database.BookDB.
ReceiptServlet, for example, calls BookDB.When a user makes a purchase, the buyBooks method is used to update the book inventory. The buyBooks function calls buyBook for each book in the shopping basket. To ensure that the complete order is processed, the buy-Book calls are wrapped in a single JDBC transaction. The use of the shared database connection is synchronised using the [get|release]Connection methods.
Servlet Database Access
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()); } } }
Initializing a Servlet
The Web container initialises the servlet after it loads and instantiates the servlet class and before it sends requests from clients. By overriding the init method of the Servlet interface, you can customise this procedure to allow the servlet to read permanent configuration data, initialise resources, and do any other one-time tasks. A servlet that cannot complete its initialization process should throw UnavailableException.
All of the servlets that interact with the bookstore database (BookStoreServlet, CatalogServlet, BookDetailsServlet, and ShowCartServlet) set a variable in their init function that points to the database helper object created by the Web context listener:
public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } }
A servlet’s service is implemented in the service method of a GenericServlet, the doMethod methods of a HttpServlet (where Method can take the value Get, Delete, Options, Post, Put, Trace), or any other protocol-specific methods defined by a class that implements the Servlet interface.