Showing posts with label initializing a servlet. Show all posts
Showing posts with label initializing a servlet. Show all posts

Thursday, 15 December 2011

Finalizing a Servlet


When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources, or when it is being shut down), it calls thedestroy method of the Servlet interface. In this method, you release any resources the servlet is using and save any persistent state. The following destroy method releases the database object created in the init method described in Initializing a Servlet:
public void destroy() {
   bookDB = null;
}
 
All of a servlet's service methods should be complete when a servlet is removed. The server tries to ensure this completion by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first.
If your servlet has potentially long-running service requests, use the techniques described below to do the following:
  • Keep track of how many threads are currently running the service method.
  • Provide a clean shutdown by having the destroy method notify long-running threads of the shutdown and wait for them to complete.
  • Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.

Invoking Other Web Resources


Web components can invoke other Web resources in two ways: indirect and direct. A Web component indirectly invokes another Web resource when it embeds in content returned to a client a URL that points to another Web component. In the Duke's Bookstore application, most Web components contain embedded URLs that point to other Web components. For example,ShowCartServlet indirectly invokes the CatalogServlet through the embedded URL /bookstore1/catalog.
A Web component can also directly invoke another resource while it is executing. There are two possibilities: it can include the content of another resource, or it can forward a request to another resource.
To invoke a resource available on the server that is running a Web component, you must first obtain a RequestDispatcher object using the getRequestDispatcher("URL") method.
You can get a RequestDispatcher object from either a request or the Web context; however, the two methods have slightly different behavior. The method takes the path to the requested resource as an argument. A request can take a relative path (that is, one that does not begin with a /), but the Web context requires an absolute path. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.
Read more on Web Resource 

Writing Service Methods - Servlets


Read Initialization of Servlet from Servlet Tutorial Part 1 

Writing Service Methods

The service provided by a servlet is implemented in the service method of a GenericServlet, the doMethod methods (where Method can take the value GetDeleteOptionsPostPut,Trace) of an HttpServlet, or any other protocol-specific methods defined by a class that implements the Servlet interface. In the rest of this chapter, the term service method will be used for any method in a servlet class that provides a service to a client.
The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information.
For HTTP servlets, the correct procedure for populating the response is to first fill in the response headers, then retrieve an output stream from the response, and finally write any body content to the output stream. Response headers must always be set before a PrintWriter or ServletOutputStream is retrieved because the HTTP protocol expects to receive all headers before body content. The next two sections describe how to get information from requests and generate responses.

Getting Information from Requests

A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information:
  • Parameters, which are typically used to convey information between clients and servlets
  • Object-valued attributes, which are typically used to pass information between the servlet container and a servlet or between collaborating servlets
  • Information about the protocol used to communicate the request and the client and server involved in the request
  • Information relevant to localization
For example, in CatalogServlet the identifier of the book that a customer wishes to purchase is included as a parameter to the request. The following code fragment illustrates how to use thegetParameter method to extract the identifier:
String bookId = request.getParameter("Add");
if (bookId != null) {
   BookDetails book = bookDB.getBookDetails(bookId);
 
You can also retrieve an input stream from the request and manually parse the data. To read character data, use the BufferedReader object returned by the request's getReader method. To read binary data, use the ServletInputStream object returned by getInputStream.
HTTP servlets are passed an HTTP request object, HttpServletRequest, which contains the request URL, HTTP headers, query string, and so on.
An HTTP request URL contains the following parts:
http://<host>:<port><request path>?<query string>
 
The request path is further composed of the following elements:
  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's J2EE application.
  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
  • Path info: The part of the request path that is not part of the context path or the servlet path.
If the context path is /catalog, and the aliases are as listed in Table 10-5, then Table 10-6 gives some examples of how the URL will be broken down:
Table 10-5 Aliases 
PatternServlet
/lawn/*LawnServlet
/*.jspJSPServlet

Table 10-6 Request Path Elements 
Request PathServlet PathPath Info
/catalog/lawn/index.html/lawn/index.html
/catalog/help/feedback.jsp/help/feedback.jspnull
Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request with the getParameter method. There are two ways to generate query strings:
  • A query string can explicitly appear in a Web page. For example, an HTML page generated by CatalogServlet could contain the link
       <a href="/bookstore1/catalog?Add=101">Add To Cart</a>
     
    
    CatalogServlet extracts the parameter named Add as follows:
    String bookId = request.getParameter("Add");
     
    

  • A query string is appended to a URL when a form with a GET HTTP method is submitted. In the Duke's Bookstore application, CashierServlet generates a form, then a user name input to the form is appended to the URL that maps to ReceiptServlet, and finally ReceiptServlet extracts the user name using the getParameter method.

Constructing Responses

A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to do the following:
  • Retrieve an output stream to use to send data to the client. To send character data, use the PrintWriter returned by the response's getWriter method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream. To mix binary and text data, for example, to create a multipart response, use a ServletOutputStreamand manage the character sections manually.
  • Indicate the content type (for example, text/html), being returned by the response. A registry of content type names is kept by the Internet Assigned Numbers Authority (IANA) at:
    ftp://ftp.isi.edu/in-notes/iana/assignments/media-types
     
    
  • Indicate whether to buffer output. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is actually sent back to the client, thus providing the servlet with more time to set appropriate status codes and headers or forward to another Web resource.
  • Set localization information.
HTTP response objects, HttpServletResponse, have fields representing HTTP headers such as
  • Status codes, which are used to indicate the reason a request is not satisfied.
  • Cookies, which are used to store application-specific information at the client. Sometimes cookies are used to maintain an identifier for tracking a user's session.
In Duke's Bookstore, BookDetailsServlet generates an HTML page that displays information about a book that the servlet retrieves from a database. The servlet first sets response headers: the content type of the response and the buffer size. The servlet buffers the page content because the database access can generate an exception that would cause forwarding to an error page. By buffering the response, the client will not see a concatenation of part of a Duke's Bookstore page with the error page should an error occur. The doGet method then retrieves a PrintWriterfrom the response.
For filling in the response, the servlet first dispatches the request to BannerServlet, which generates a common banner for all the servlets in the application. This process is discussed in the section Including Other Resources in the Response. Then the servlet retrieves the book identifier from a request parameter and uses the identifier to retrieve information about the book from the bookstore database. Finally, the servlet generates HTML markup that describes the book information and commits the response to the client by calling the close method on the PrintWriter.
public class BookDetailsServlet extends HttpServlet { 
    public void doGet (HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException, IOException {
      // set headers before accessing the Writer
      response.setContentType("text/html");
      response.setBufferSize(8192);
      PrintWriter out = response.getWriter();

      // then write the response
      out.println("<html>" +
         "<head><title>+
         messages.getString("TitleBookDescription")
         +</title></head>");

      // Get the dispatcher; it gets the banner to the user
      RequestDispatcher dispatcher =
         getServletContext().
         getRequestDispatcher("/banner");
      if (dispatcher != null)
         dispatcher.include(request, response);

      //Get the identifier of the book to display
      String bookId = request.getParameter("bookId");
      if (bookId != null) {
         // and the information about the book
         try {
            BookDetails bd =
               bookDB.getBookDetails(bookId);
            ...
            //Print out the information obtained
            out.println("<h2>" + bd.getTitle() + "</h2>" +
            ...
         } catch (BookNotFoundException ex) {
            response.resetBuffer();
            throw new ServletException(ex);
         }
      }
      out.println("</body></html>");
      out.close();
   }
}

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. You can customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding 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 (BookStoreServletCatalogServletBookDetailsServlet, and ShowCartServlet) initialize a variable in their init method 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.");
   }
}