Servlets
Overview
The first, and a still important, technology for delivering dynamic content on web was CGI. Java Servlets are a more scalable and portable way dynamic, user-oriented content.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.
When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
Bookstore Example
BookDetailsServlet illustrates how to handle HTTP GET requests, BookDetailsServlet and CatalogServlet show how to construct responses, and CatalogServlet illustrates how to track session information.
Servlet Function BookStoreServlet Enter the bookstore BannerServlet Create the bookstore banner CatalogServlet Browse the bookstore catalog CatalogServlet,
BookDetailsServletPut a book in a shopping cart BookDetailsServlet Get details on a specific book ShowCartServlet Display the shopping cart ShowCartServlet Remove one or more books from the shopping cart CashierServlet Buy the books in the shopping cart ReceiptServlet Receive an acknowledgement for the purchase The data for the bookstore application is maintained in a database and accessed through the helper class database.BookDB. The database package also contains the class BookDetails, which represents a book. The shopping cart and shopping cart items are represented by the classes cart.ShoppingCart and cart.ShoppingCartItem, respectively.
The source code for the bookstore application is located in the $JWSDP_HOME/docs/tutorial/examples/web/bookstore1 directory created when you unzip the tutorial bundle (see Running the Examples).
To build, install, and run the example:
- In a terminal window, go to $JWSDP_HOME/docs/tutorial/examples/web/bookstore1.
- Run ant build. The build target will spawn any necessary compilations and copy files to the $JWSDP_HOME/docs/tutorial/examples/web/bookstore1/build directory.
- Make sure Tomcat is started.
- Run ant install. The install target notifies Tomcat that the new context is available.
- Start the PointBase database server and populate the database if you have not done so already (see Accessing Databases from Web Applications).
- To run the application, open the bookstore URL http://localhost:8080/bookstore1/enter.
To use the Ant deploy task to deploy the application:
- Run ant package. The package task creates a WAR file containing the application classes in WEB-INF/classes and the context.xml file in META-INF.
- Make sure Tomcat is started.
- Run ant deploy. The deploy target copies the WAR to Tomcat and notifies Tomcat that the new context is available.
To use deploytool to deploy the application:
- Make sure Tomcat is started.
- Start deploytool.
- Create a webapp called bookstore1.
- Select FileNew Web Application.
- Click Browse.
- In the file chooser, navigate to $JWSDP_HOME/docs/tutorial/examples/web/bookstore1/build.
- In the File Name field, enter bookstore1.
- Click Choose Module File.
- In the WAR Display Name field, enter bookstore1.
- In the Edit Archive Contents dialog box, navigate to $JWSDP_HOME/docs/tutorial/examples/web/bookstore1/build. Select errorpage.html and duke.books.gif and click Add. Navigate to WEB-INF/classes, and select BannerServlet.class, BookStoreServlet.class, BookDetailsServlet.class, CatalogServlet.class, ShowCartServlet.class, CashierServlet.class, and ReceiptServlet.class. and the cart, database, exception, filters, listeners, messages, and util packages. Click Add, then click OK.
- Click Next.
- Select the Servlet radio button.
- Click Next.
- Select BannerServlet from the Servlet Class combo box.
- Click Finish.
- Add each of the Web components listed in Table 12-2. For each servlet:
- Select FileEdit Web Application.
- Click the Add to Existing WAR Module radio button Since the WAR contains all of the servlet classes, you do not have to add any more content.
- Click Next.
- Select the Servlet radio button.
- Click Next.
- Select the servlet from the Servlet Class combo box.
- Click Finish.
Web Component Name
Servlet Class
Component Alias
BookStoreServlet BookStoreServlet /enter CatalogServlet CatalogServlet /catalog BookDetailsServlet BookDetailsServlet /bookdetails ShowCartServlet ShowCartServlet /showcart CashierServlet CashierServlet /cashier ReceiptServlet ReceiptServlet /receipt - Add aliases for each of the components.
- Select the component.
- Select the Aliases tab.
- Click Add and then type the alias in the Aliases field.
- Add the listener class listeners.ContextListener (described in Handling Servlet Life Cycle Events).
- Add an error page (described in Handling Errors.
- Select the File Refs tab.
- Click Add in the Error Mapping panel.
- Enter exception.BookNotFoundException in the Error/Exception field.
- Enter /errorpage.html in the Resource to be Called field.
- Repeat for exception.BooksNotFoundException and javax.servlet.UnavailableException.
- Add the filters filters.HitCounterFilter and filters.OrderFilter (described in Filtering Requests and Responses).
- Select the Filter Mapping tab.
- Click Edit Filter List.
- Click Add.
- Select filters.HitCounterFilter from the Filter Class column. The deploytool will automatically enter HitCounterFilter in the Display Name column.
- Click Add.
- Select filters.OrderFilter from the Filter Class column. The deploytool will automatically enter OrderFilter in the Display Name column.
- Click OK.
- Click Add.
- Select HitCounterFilter from the Filter Name column.
- Select Servlet from the Target Type column.
- Select BookStoreServlet from the Target column.
- Repeat for OrderFilter. The target type is Servlet and the target is ReceiptServlet.
- Add a resource reference for the database.
- Select the WAR.
- Select the Resource Refs tab.
- Click Add.
- Select javax.sql.DataSource from the Type column
- Enter jdbc/BookDB in the Coded Name field.
- Click the Import Data Sources button.
- Dismiss the confirmation dialog.
- Select pointbase from the drop down list.
- Deploy the application.
- Select Tools->Deploy.
- Click OK to select the default context path /bookstore1.
- Click Finish.
Troubleshooting
Common Problems and Their Solutions lists some reasons why a Web client can fail. In addition, Duke's Bookstore returns the following exceptions:
- BookNotFoundException--Returned if a book can't be located in the bookstore database. This will occur if you haven't loaded the bookstore database with data by running ant create-book-db or if the database server hasn't been started or it has crashed.
- BooksNotFoundException--Returned if the bookstore data can't be retrieved. This will occur if you haven't loaded the bookstore database with data by running ant create-book-db or if the database server hasn't been started or it has crashed.
- UnavailableException--Returned if a servlet can't retrieve the Web context attribute representing the bookstore. This will occur if you haven't copied the PointBase client library <PB_HOME>/lib/pbclient42.jar to $JWSDP_HOME/common/lib, if the PointBase server hasn't been started, or if you have not defined a data source in Tomcat that references the PointBase database (see Defining a Data Source in Tomcat).
Because we have specified an error page, you will see the message The application is unavailable. Please try later. If you don't specify an error page, the Web container generates a default page containing the message A Servlet Exception Has Occurred and a stack trace that can help diagnose the cause of the exception. If you use the errorpage.html, you will have to look in the Web container's log to determine the cause of the exception. Web log files reside in the directory $JWSDP_HOME/logs and are named jwsdp_log.<date>.txt.
Servlet Life Cycle
The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
- If an instance of the servlet does not exist, the Web container
- Loads the servlet class.
- Creates an instance of the servlet class.
- Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
- Invokes the service method, passing a request and response object. Service methods are discussed in Writing Service Methods.
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method. Finalization is discussed in Finalizing a Servlet.
Handling Servlet Life Cycle Events
You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when life cycle events occur. To use these listener objects define the listener class and specify the listener class.
Defining The Listener Class
You define a listener class as an implementation of a listener interface. Servlet Life Cycle Events lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed