Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Servlet Overview and Architecture - Servlets

Chapter: Internet & World Wide Web HOW TO PROGRAM - Servlets: Bonus for Java™ Developers

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Servlet Overview and Architecture - Servlets

The primary purpose of an HTTP get request is to retrieve the content of a specified URL—normally the content is an HTML or XHTML document (i.e., a Web page).

Handling HTTP get Requests


The primary purpose of an HTTP get request is to retrieve the content of a specified URL—normally the content is an HTML or XHTML document (i.e., a Web page). The servlet of Fig. 30.5 and the XHTML document of Fig. 30.6 demonstrate a servlet that han-dles HTTP get requests. When the user clicks the Get HTML Document button (Fig. 30.6), a get request is sent to the servlet WelcomeServlet (Fig. 30.5). The servlet responds to the request by generating dynamically an XHTML document for the client that displays “Welcome to Servlets!”. Figure 30.5 shows the WelcomeServlet source code. Figure 30.6 shows the XHTML document the client loads to access the servlet and shows screen captures of the client’s browser window before and after the interaction with the servlet. [Note: Section 30.3.1 discusses how to set up and configure Tomcat to ex-ecute this example.]



    // Fig. 9.5: WelcomeServlet.java

    // A simple servlet to process get requests.

    package com.deitel.advjhtp1.servlets;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class WelcomeServlet extends HttpServlet {


      // process "get" requests from clients

      protected void doGet( HttpServletRequest request,

      HttpServletResponse response )

      throws ServletException, IOException


      response.setContentType( "text/html" );

PrintWriter out = response.getWriter();

            // send XHTML page to client



            // start XHTML document

            out.println( "<?xml version = \"1.0\"?>" );


            out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +

            "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

            "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );



            "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

      // head section of document

      out.println( "<head>" );

      out.println( "<title>A Simple Servlet Example</title>" );

      out.println( "</head>" );

      // body section of document

      out.println( "<body>" );

      out.println( "<h1>Welcome to Servlets!</h1>" );

      out.println( "</body>" );

      // end XHTML document

      out.println( "</html>" );

      out.close();  // close stream to complete the page




Fig. 30.5 WelcomeServlet handles a simple HTTP get request


Lines 5 and 6 import the javax.servlet and javax.servlet.http packages. We use several data types from these packages in the example.


Package javax.servlet.http provides superclass HttpServlet for servlets that handle HTTP get requests and HTTP post requests. This class implements interface javax.servlet.Servlet and adds methods that support HTTP protocol requests. Class WelcomeServlet extends HttpServlet (line 9) for this reason.


Superclass HttpServlet provides method doGet to respond to get requests. Its default functionality is to indicate a “Method not allowed” error. Typically, this error is indicated in Internet Explorer with a Web page that states “This page cannot be displayed” and in Netscape Navigator with a Web page that states “Error: 405.” We override method doGet (lines 12–44) to provide custom get request processing. Method doGet receives two arguments—an object that implements interface HttpServletRequest and an object that implements interface HttpServletResponse (both from package javax.servlet.http). The HttpServletRequest object represents the client’s request, and the HttpServletResponse object represents the server’s response to the client. If method doGet is unable to handle a client’s request, it throws an exception of type javax.servlet.ServletException. If doGet encounters an error during stream processing (reading from the client or writing to the client), it throws a java.io.IOException.

To demonstrate a response to a get request, our servlet creates an XHTML document containing the text “Welcome to Servlets!”. The text of the XHTML document is the response to the client. The response is sent to the client through the PrintWriter object obtained from the HttpServletResponse object.


Line 16 uses the response object’s setContentType method to specify the con-tent type of the data to be sent as the response to the client. This enables the client browser to understand and handle the content. The content type also is known as the MIME type (Multipurpose Internet Mail Extension) of the data. In this example, the content type is text/html to indicate to the browser that the response is an XHTML document. The browser knows that it must read the XHTML tags in the document, format the document according to the tags and display the document in the browser window. For more informa-tion on MIME types visit www.irvine.com/~mime.


Line 17 uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. [Note: If the response is binary data, such as an image, method getOutputStream is used to obtain a reference to a ServletOutputStream object.]


Lines 22–42 create the XHTML document by writing strings with the out object’s println method. This method outputs a newline character after its String argument. When rendering the Web page, the browser does not use the newline character. Rather, the newline character appears in the XHTML source that you can see by selecting Source from the View menu in Internet Explorer or Page Source from the View menu in Netscape Navigator. Line 43 closes the output stream, flushes the output buffer and sends the information to the client. This commits the response to the client.

The XHTML document in Fig. 30.6 provides a form that invokes the servlet defined in Fig. 30.5. The form’s action




specifies the URL path that invokes the servlet, and the form’s method indicates that the browser sends a get request to the server, which results in a call to the servlet’s doGet method. The URL specified as the action in this example is discussed in detail in Section 30.3.2 after we show how to set up and configure the Apache Tomcat server to ex-ecute the servlet in Fig. 30.5.



      <?xml version = "1.0"?>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"



<!-- Fig. 9.6: WelcomeServlet.html -->


      <html xmlns = "http://www.w3.org/1999/xhtml">


      <title>Handling an HTTP Get Request</title>



        <form action = "/advjhtp1/welcome1" method = "get">


              <p><label>Click the button to invoke the servlet

        <input type = "submit" value = "Get HTML Document" />






Fig. 30.6 HTML document in which the form’s action invokes WelcomeServlet through the alias welcome1 specified in web.xml


Note that the sample screen captures show a URL containing the server name local-host—a well-known server host name on most computers that support TCP/IP-based net-working protocols such as HTTP. We often use localhost to demonstrate networking programs on the local computer, so that readers without a network connection can still learn network programming concepts. In this example, localhost indicates that the server on which the servlet is installed is running on the local machine. The server host name is fol-lowed by :8080, specifying the TCP port number at which the Tomcat server awaits requests from clients. Web browsers assume TCP port 80 by default as the server port at which clients make requests, but the Tomcat server awaits client requests at TCP port 8080. This allows Tomcat to execute on the same computer as a standard Web server application without affecting the Web server application’s ability to handle requests. If we do not explicitly specify the port number in the URL, the servlet never will receive our request and an error message will be displayed in the browser.

Ports in this case are not physical hardware ports to which you attach cables; rather, they are logical locations named with integer values that allow clients to request different services on the same server. The port number specifies the logical location where a server waits for and receives connections from clients—this is also called the handshake point. When a client connects to a server to request a service, the client must specify the port number for that service; otherwise, the client request cannot be processed. Port numbers are positive integers with values up to 65,535, and there are separate sets of these port numbers for both the TCP and UDP protocols. Many operating systems reserve port num-bers below 1024 for system services (such as email and World Wide Web servers). Gen-erally, these ports should not be specified as connection ports in your own server programs. In fact, some operating systems require special access privileges to use port numbers below 1024.


With so many ports from which to choose, how does a client know which port to use when requesting a service? The term well-known port number often is used when describing popular services on the Internet such as Web servers and email servers. For example, a Web server waits for clients to make requests at port 80 by default. All Web browsers know this number as the well-known port on a Web server where requests for HTML documents are made. So when you type a URL into a Web browser, the browser normally connects to port 80 on the server. Similarly, the Tomcat server uses port 8080 as its port number. Thus, requests to Tomcat for Web pages or to invoke servlets and Java-Server Pages must specify that the Tomcat server waiting for requests on port 8080.


The client can access the servlet only if the servlet is installed on a server that can respond to servlet requests. In some cases, servlet support is built directly into the Web server, and no special configuration is required to handle servlet requests. In other cases, it is necessary to integrate a servlet container with a Web server (as can be done with Tomcat and the Apache or IIS Web servers). Web servers that support servlets normally have an installation procedure for servlets. If you intend to execute your servlet as part of a Web server, please refer to your Web server’s documentation on how to install a servlet. For our examples, we demonstrate servlets with the Apache Tomcat server. Section 30.3.1 dis-cusses the setup and configuration of Tomcat for use with this chapter. Section 30.3.2 dis-cusses the deployment of the servlet in Fig. 30.5.


1. Setting Up the Apache Tomcat Server


Tomcat is a fully functional implementation of the JSP and servlet standards. It includes a Web server, so it can be used as a standalone test container for JSPs and servlets. Tomcat also can be specified as the handler for JSP and servlet requests received by popular Web servers such as the Apache Software Foundation’s Apache Web server or Microsoft’s In-ternet Information Server (IIS). Tomcat is integrated into the Java 2 Enterprise Edition ref-erence implementation from Sun Microsystems.


The most recent release of Tomcat (version 3.2.3) can be downloaded from




where there are a number of archive files. The complete Tomcat implementation is con-tained in the files that begin with the name jakarta-tomcat-3.2.3. Zip, tar and com-pressed tar files are provided for Windows, Linux and Solaris.


Extract the contents of the archive file to a directory on your hard disk. By default, the name of the directory containing Tomcat is jakarta-tomcat-3.2.3. For Tomcat to work correctly, you must define environment variables JAVA_HOME and TOMCAT_HOME. JAVA_HOME should point to the directory containing your Java installation (ours is d:\jdk1.3.1), and TOMCAT_HOME should point to the directory that contains Tomcat (ours is d:\jakarta-tomcat-3.2.3).


After setting the environment variables, you can start the Tomcat server. Open a com-mand prompt (or shell) and change directories to bin in jakarta-tomcat-3.2.3. In this directory are the files tomcat.bat and tomcat.sh, for starting the Tomcat server on Windows and UNIX (Linux or Solaris), respectively. To start the server, type


tomcat start


This launches the Tomcat server. The Tomcat server executes on TCP port 8080 to prevent conflicts with standard Web servers that typically execute on TCP port 80. To prove that Tomcat is executing and can respond to requests, open your Web browser and enter the URL




This should display the Tomcat documentation home page (Fig. 30.7). The host local-host indicates to the Web browser that it should request the home page from the Tomcat server on the local computer.


Fig. 30.7 Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)

If the Tomcat documentation home page does not display, try the URL


The host localhost translates to the IP address


To shut down the Tomcat server, issue the command


tomcat stop


from a command prompt (or shell).


2. Deploying a Web Application


JSPs, servlets and their supporting files are deployed as part of Web applications. Normal-ly, Web applications are deployed in the webapps subdirectory of jakarta-tomcat-3.2.3. A Web application has a well-known directory structure in which all the files that are part of the application reside. This directory structure can be created by the server ad-ministrator in the webapps directory, or the entire directory structure can be archived in a Web application archive file. Such an archive is known as a WAR file and ends with the


.war file extension. If a WAR file is placed in the webapps directory, then, when the Tomcat server begins execution, it extracts the contents of the WAR file into the appropri-ate webapps subdirectory structure. For simplicity as we teach servlets and JavaServer Pages, we create the already expanded directory structure that will be used for all the ex-amples in this chapter and Chapter 31.

The Web application directory structure has a context root—the top-level directory for an entire Web application—and several subdirectories. These are described in Fig. 30.8.


Before we can deploy our Web application for the WelcomeServlet of Fig. 30.5, we must make the servlet container (i.e., Tomcat) aware of the context root for our Web application. We accomplish this by editing the file server.xml in the conf subdirec-tory of jakarta-tomcat-3.2.3. This XML file describes the configuration of the Tomcat server. Open this file, scroll toward the bottom and locate the section that starts with the comment “Special webapps.” In this section, there are XML Context ele-ments that describe the context roots for the Tomcat examples and admin Web appli-cations.


We will create a Context called advjhtp1 to serve as the context root for most of our JSP and servlet examples. To create the advjhtp1 context root, edit the server.xml file, and insert the Context element of Fig. 30.9 after the Context ele-ment for admin; then save the server.xml file.

Line 2 begins the Context element and specifies its path attribute. The server uses the path to determine which Web application receives the request. In particular, attribute path specifies the initial part of the path in a URL that requests a Web application. The path is the part of the URL following the host name and optional port number. Attribute docBase specifies the subdirectory of webapps in which the Web application files are located.

Now that Tomcat is configured for our context root, we need to configure our Web application to handle the requests. To simplify the deployment of the examples in this chapter, WAR files are not used. Rather, we place the example files in directory advjhtp1 or the relevant subdirectory. We discuss WAR files in detail as part of the servlet case study in the next chapter.


Deploying a Web application requires the creation of a deployment descriptor (stored in a file called web.xml) that specifies various configuration parameters such as the name used to invoke the servlet, a description of the servlet, the class name of the servlet class and a servlet mapping, i.e., the path or paths that cause the servlet to be invoked. You must create the web.xml file for this example. Many Java Web applica-tion deployment tools create this file for you. The web.xml file for the first example in this chapter is shown in Fig. 30.10. This file will be enhanced as we add other servlets to the Web application.



    <!-- Advanced Java How to Program JSP/servlet context -->

    <Context path = "/advjhtp1"

                 docBase = "webapps/advjhtp1"

    reloadable = "true">


     Fig. 30.9    Context element for servlet and JSP examples in Chapters 30 and 31.





    <!DOCTYPE web-app PUBLIC

    "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"




    <!-- General description of your Web application -->


    Advanced Java How to Program JSP

      and Servlet Chapter Examples



      This is the Web application in which we

      demonstrate our JSP and Servlet examples.


      <!-- Servlet definitions -->





      A simple servlet that handles an HTTP get request.






      <!-- Servlet mappings -->







Fig. 30.10  Deployment descriptor for the advjhtp1 Web application.


Lines 1–3 specify the document type for the Web application deployment descriptor and the location of the DTD for this XML file. Element web-app (lines 5–37) defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. Element display-name (lines 8–11) specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description (lines 13–16) specifies a description of the Web application that might be displayed to the administrator of the server.


Element servlet (lines 19–29) describes a servlet. Element servlet-name (line is the name we chose for the servlet (welcome1). Element description (lines 22–specifies a description for this particular servlet. Again, this can be displayed to the administrator of the Web server. Element servlet-class (lines 26–28) specifies compiled servlet’s fully qualified class name. Thus, the servlet welcome1 is defined by class



Element servlet-mapping (lines 32–35) specifies servlet-name and url-pattern elements. The URL pattern helps the server determine which requests are sent to the servlet (welcome1). Our Web application will be installed as part of the advjhtp1 context root—specified as part of the Context element discussed in Fig. 30.9 that we added to the server.xml file). Thus, the URL we supply to the browser to invoke the servlet in this example is




where /advjhtp1 specifies the context root that helps the server determine which Web application handles the request and /welcome1 specifies the URL pattern that is mapped to servlet welcome1 to handle the request. Note that the server on which the servlet re-sides is not specified here, although it is possible to do so as follows:




If the explicit server and port number are not specified as part of the URL, the browser as-sumes that the form handler (i.e., the servlet specified in the action property of the form element) resides at the same server and port number from which the browser downloaded the Web page containing the form.


There are several URL pattern formats that can be used. The /welcome1 URL pat-tern requires an exact match of the pattern. You can also specify path mappings, extension mappings and a default servlet for a Web application. A path mapping begins with a / and ends with a /*. For example, the URL pattern



indicates that any URL path beginning with /advjhtp1/example/ will be sent to the servlet that has the preceding URL pattern. An extension mapping begins with *. and ends with a file name extension. For example, the URL pattern




indicates that any request for a file with the extension .jsp will be sent to the servlet that handles JSP requests. In fact, servers with JSP containers have an implicit mapping of the


.jsp extension to a servlet that handles JSP requests. The URL pattern / represents the default servlet for the Web application. This is similar to the default document of a Web server. For example, if you type the URL www.deitel.com into your Web browser, the document you receive from our Web server is the default document index.html. If the URL pattern matches the default servlet for a Web application, that servlet is invoked to return a default response to the client. This can be useful for personalizing Web content to specific users. We discuss personalization in Section 30.7, Session Tracking.


Finally, we are ready to place our files into the appropriate directories to complete the deployment of our first servlet, so we can test it. There are three files we must place in the appropriate directories—WelcomeServlet.html, WelcomeServlet.class and web.xml. In the webapps subdirectory of your jakarta-tomcat-3.2.3 directory, create the advjhtp1 subdirectory that represents the context root for our Web applica tion. In this directory, create subdirectories named servlets and WEB-INF. We place our HTML files for this servlets chapter in the servlets directory. Copy the Wel-comeServlet.html file into the servlets directory. In the WEB-INF directory, create the subdirectory classes, then copy the web.xml file into the WEB-INF direc-tory, and copy the WelcomeServlet.class file, including all its package name direc-tories, into the classes directory. Thus, the directory and file structure under the webapps directory should be as shown in Fig. 30.11 (file names are in italics).


After the files are placed in the proper directories, start the Tomcat server, open your browser and type the following URL—




—to load WelcomeServlet.html into the Web browser. Then, click the Get HTML Document button to invoke the servlet. You should see the results shown in Fig. 30.6. You can try this servlet from several different Web browsers to demonstrate that the results are the same across Web browsers.

WelcomeServlet Web application directory and file structure

























Actually, the HTML file in Fig. 30.6 was not necessary to invoke this servlet. A get request can be sent to a server simply by typing the URL in the Web browser. In fact, that is exactly what you are doing when you request a Web page in the browser. In this example, you can type




in the Address or Location field of your browser to invoke the servlet directly.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.