Sunday, March 6, 2011

What Is a Servlet?

What Is a Servlet?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

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.

This chapter focuses on writing servlets that generate responses to HTTP
requests. Some knowledge of the HTTP protocol is assumed; if you are unfamiliar with this protocol, you can get a brief introduction to HTTP in Appendix A.

The Example Servlets

This chapter uses the Duke's Bookstore application to illustrate the tasks involved in programming servlets. Table 10-1 lists the servlets that handle each bookstore function. Each programming task is illustrated by one or more servlets. For 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.

Table 10-1 Duke's Bookstore Example Servlets Function
Servlet
Enter the bookstore
BookStoreServlet
Create the bookstore banner
BannerServlet
Browse the bookstore catalog
CatalogServlet
Put a book in a shopping cart
CatalogServlet,
BookDetailsServlet
Get detailed information on a specific book
BookDetailsServlet
Display the shopping cart
ShowCartServlet
Remove one or more books from the shopping cart
ShowCartServlet
Buy the books in the shopping cart
CashierServlet
Receive an acknowledgement for the purchase
ReceiptServlet

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 j2eetutorial/examples/src/web/bookstore1 directory created when you unzip the tutorial bundle (see Downloading the Examples). To build, deploy, and run the example, follow these steps.

1. Go to j2eetutorial/examples and build the example by running ant bookstore1 (see How to Build and Run the Examples).
2. Start the j2ee server.
3. Start deploytool.
4. Start the Cloudscape database server by running cloudscape -start.
5. Load the bookstore data into the database by running ant create-web-db.
6. Create a J2EE application called Bookstore1App.
1. Select FileNewApplication.
2. In the file chooser, navigate to j2eetutorial/examples/src/web/bookstore1.
3. In the File Name field, enter Bookstore1App.
4. Click New Application.
5. Click OK.
7. Create the WAR and add the BannerServlet Web component and all of the Duke's Bookstore content to the Bookstore1App application.
1. Select FileNewWeb Component.
2. Click the Create New WAR File In Application radio button and select Bookstore1App from the combo box. Enter Bookstore1WAR in the field labeled WAR Display Name.
3. Click Edit to add the content files.
4. In the Edit Archive Contents dialog box, navigate to j2eetutorial/examples/build/web/bookstore1. Select BannerServlet.class, BookStoreServlet.class, BookDetailsServlet.class, CatalogServlet.class, ShowCartServlet.class, CashierServlet.class, and ReceiptServlet.class. Click Add. Add errorpage.html and duke.books.gif. Add the cart, database, exception, filters, listeners, messages, and util packages. Click OK.
5. Click Next.
6. Select the Servlet radio button.
7. Click Next.
8. Select BannerServlet from the Servlet Class combo box.
9. Click Next twice.
10. In the Component Aliases pane, click Add and then type /banner in the Alias field.
11. Click Finish.
8. Add each of the Web components listed in Table 10-2. For each servlet, click the Add to Existing WAR File radio button and select Bookstore1WAR from the combo box. Since the WAR contains all of the servlet classes, you do not have to add any more content.

Table 10-2 Duke's Bookstore Web Components 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
9. Add a resource reference for the Cloudscape database.
1. Select Bookstore1WAR.
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. Enter jdbc/Cloudscape in the JNDI Name field.
10. 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 the drop-down field in the Event Listener Classes pane.
11. Add an error page (described in Handling Errors).
1. Select the File Refs tab.
2. In the Error Mapping panel, click Add.
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.
12. 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 utility will automatically enter HitCounterFilter in the Display Name column.
5. Click Add.
6. Select filters.OrderFilter from the Filter Class column. The deploytool utility 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.
13. Enter the context root.
1. Select Bookstore1App.
2. Select the Web Context tab.
3. Enter bookstore1.
14. Deploy the application.
1. Select ToolsDeploy.
2. Click Finish.
15. Open the bookstore URL http://:8000/bookstore1/enter.

Troubleshooting

The section Common Problems and Their Solutions (in particular, Web Client Runtime Errors) 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-web-db or if the Cloudscape 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-web-db or if the Cloudscape server hasn't been started or has crashed.
* UnavailableException: Returned if a servlet can't retrieve the Web context attribute representing the bookstore. This will occur if you haven't added the listener class to the application.

Since 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 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

$J2EE_HOME/logs//web


and are named catalina..log.

The element is the directory specified by the log.directory entry in the default.properties file. The default value is logs. The element is the name of the computer. See the Configuration Guide provided with the J2EE SDK for more information about J2EE SDK log files.

1 comments:

suni said...

thanks for useful data