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,
BookDetailsServlet
Put 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:

  1. In a terminal window, go to $JWSDP_HOME/docs/tutorial/examples/web/bookstore1.
  2. 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.
  3. Make sure Tomcat is started.
  4. Run ant install. The install target notifies Tomcat that the new context is available.
  5. Start the PointBase database server and populate the database if you have not done so already (see Accessing Databases from Web Applications).
  6. To run the application, open the bookstore URL http://localhost:8080/bookstore1/enter.

To use the Ant deploy task to deploy the application:

  1. 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.
  2. Make sure Tomcat is started.
  3. 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:

  1. Make sure Tomcat is started.
  2. Start deploytool.
  3. Create a webapp called bookstore1.
    1. Select FileNew Web Application.
    2. Click Browse.
    3. In the file chooser, navigate to $JWSDP_HOME/docs/tutorial/examples/web/bookstore1/build.
    4. In the File Name field, enter bookstore1.
    5. Click Choose Module File.
    6. In the WAR Display Name field, enter bookstore1.
    7. 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.
    8. Click Next.
    9. Select the Servlet radio button.
    10. Click Next.
    11. Select BannerServlet from the Servlet Class combo box.
    12. Click Finish.
  4. Add each of the Web components listed in Table 12-2. For each servlet:
    1. Select FileEdit Web Application.
    2. 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.
    3. Click Next.
    4. Select the Servlet radio button.
    5. Click Next.
    6. Select the servlet from the Servlet Class combo box.
    7. 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
  5. Add aliases for each of the components.
    1. Select the component.
    2. Select the Aliases tab.
    3. Click Add and then type the alias in the Aliases field.
  6. Add the listener class listeners.ContextListener (described in Handling Servlet Life Cycle Events).
    1. Select the Event Listeners tab.
    2. Click Add.
    3. Select the listeners.ContextListener class from drop down field in the Event Listener Classes panel.
  7. Add an error page (described in Handling Errors.
    1. Select the File Refs tab.
    2. Click Add in the Error Mapping panel.
    3. Enter exception.BookNotFoundException in the Error/Exception field.
    4. Enter /errorpage.html in the Resource to be Called field.
    5. Repeat for exception.BooksNotFoundException and javax.servlet.UnavailableException.
  8. Add the filters filters.HitCounterFilter and filters.OrderFilter (described in Filtering Requests and Responses).
    1. Select the Filter Mapping tab.
    2. Click Edit Filter List.
    3. Click Add.
    4. Select filters.HitCounterFilter from the Filter Class column. The deploytool will automatically enter HitCounterFilter in the Display Name column.
    5. Click Add.
    6. Select filters.OrderFilter from the Filter Class column. The deploytool will automatically enter OrderFilter in the Display Name column.
    7. Click OK.
    8. Click Add.
    9. Select HitCounterFilter from the Filter Name column.
    10. Select Servlet from the Target Type column.
    11. Select BookStoreServlet from the Target column.
    12. Repeat for OrderFilter. The target type is Servlet and the target is ReceiptServlet.
  9. Add a resource reference for the database.
    1. Select the WAR.
    2. Select the Resource Refs tab.
    3. Click Add.
    4. Select javax.sql.DataSource from the Type column
    5. Enter jdbc/BookDB in the Coded Name field.
    6. Click the Import Data Sources button.
    7. Dismiss the confirmation dialog.
    8. Select pointbase from the drop down list.
  10. Deploy the application.
    1. Select Tools->Deploy.
    2. Click OK to select the default context path /bookstore1.
    3. 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:

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.

  1. If an instance of the servlet does not exist, the Web container
    1. Loads the servlet class.
    2. Creates an instance of the servlet class.
    3. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
  2. 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