background image

Initializing a Servlet

<< The Database Access Class | Writing Service Methods >>
<< The Database Access Class | Writing Service Methods >>

Initializing a Servlet

To ensure that the order is processed in its entirety, the call to buyBooks is wrapped in a single
transaction. In the following code, the calls to the begin and commit methods of
UserTransaction
mark the boundaries of the transaction. The call to the rollback method of
UserTransaction
undoes the effects of all statements in the transaction so as to protect the
integrity of the data.
try {
utx.begin();
bookDB.buyBooks(cart);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch(Exception e) {
System.out.println(
"Rollback failed: "+e.getMessage());
}
System.err.println(ex.getMessage());
orderCompleted = false;}
}
Initializing a Servlet
After the web container loads and instantiates the servlet class and before it delivers requests
from clients, the web container initializes the servlet. To customize this process to allow the
servlet to read persistent configuration data, initialize resources, and perform any other
one-time activities, you override the init method of the Servlet interface. A servlet that
cannot complete its initialization process should throw UnavailableException.
All the servlets that access the bookstore database (BookStoreServlet, CatalogServlet,
BookDetailsServlet
, and ShowCartServlet) initialize a variable in their init method that
points to the database access object created by the web context listener:
public class CatalogServlet 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.");
}
}
Initializing a Servlet
Chapter 4 · Java Servlet Technology
109