October 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Understanding Servlets

  • April 8, 2003
  • By Steven Haines and Steven Potts
  • Send Email »
  • More Articles »

Most of the work that you will do with Tomcat will involve four of the directories located under the root Tomcat directory. These directories are

  • C:\Program Files\Apache Tomcat 4.0\bin—This directory contains scripts to perform functions such as startup, shutdown, and so on. Under Windows, these scripts are .bat files, and under Unix, they are .sh files.

  • C:\Program Files\Apache Tomcat 4.0\conf—This directory contains configuration files, which control the behavior of the server. Most of these files are in XML format. The most important file in here is called server.xml, the main configuration file for the server.

  • C:\Program Files\Apache Tomcat 4.0\logs—This directory contains the logs that are created by the Tomcat server. You inspect these logs to discover clues about why certain problems are occurring with the installation and/or your programs.

  • C:\Program Files\Apache Tomcat 4.0\webapps—This directory is where you put your programs. Web servers don't like to access files all over your computer because of the security risks. They prefer to allow clients to access only files that are stored in one place and its subdirectories.

Testing the Installation

After you have finished the installation, you will want to test the server using servlets provided by Apache before writing your own. The reason for this is that any problem you have running their servlets is certainly a configuration problem. If you run your own servlets without first verifying that the installation is correct, the problem could be either in the installation or with your servlet.

Testing the installation is easy. First, start Tomcat by following the procedure described previously. Next, type the following command in a browser address box:

http://localhost:8080

You should immediately see a screen that looks like Figure 21.3.

Figure 21.3

The Tomcat localhost home page will display when the server is running properly.

If you do not see this page immediately, the most likely reason is that you have another program listening to port 8080. In that case, edit the file called server.xml in the C:\Program Files\Apache Tomcat 4.0\conf directory. Look for the following lines:

  <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector 
    className="org.apache.catalina.connector.http.HttpConnector"
        port="8080" minProcessors="5" maxProcessors="75"
        enableLookups="true" redirectPort="8443"
        acceptCount="10" debug="0" connectionTimeout="60000"/>

Edit the fourth line and change it to some value more than 1024, like 1776. It will look like this:

  <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
  <Connector className=
       "org.apache.catalina.connector.http.HttpConnector"
        port="1776" minProcessors="5" maxProcessors="75"
        enableLookups="true" redirectPort="8443"
        acceptCount="10" debug="0" connectionTimeout="60000"/>

Save this file and restart the Tomcat server. Repeat the test by opening a browser, but this time type

http://localhost:1776

If this doesn't open the magic Web page shown in Figure 21.3, consult the troubleshooting documentation that Tomcat installed on your hard drive.


Note - This chapter uses port 1776 for all the examples. The reason for this is that port 8080, the default Tomcat port, was already in use on our test machine.


Programming Servlets

Servlet programming is built on a solid foundation of prewritten Java classes. Instead of creating servlets as Java classes that are started by calling a main method, servlets are extensions of other classes that already know how to interact with Web servers and servlet containers.

The following classes and interfaces are the most important ones to understand when programming servlets:

  • Servlet—This interface defines the init(), service(), and destroy() methods. It also defines two more methods that implementing classes must provide, getServletConfig() and getServletInfo(), which allow you to query the servlet for information about the servlet itself (author, version, copyright, and so on). The servlet container is programmed to expect a servlet to implement these five methods. This is how code that you write can be plugged into a framework such as the servlet container so easily. Advanced programmers might want to implement this interface directly in a new class instead of using either the GenericServlet class or HttpServlet class. This would require you to write quite a bit of code, however, and it is not needed to satisfy ordinary requirements.

  • GenericServlet—The GenericServlet class provides a simple implementation of the Servlet interface. It is called "Generic" because it does not assume that the protocol it will process will be HTTP. If you were writing your own protocol, you would extend this class. Normally, you override the service() method.

  • HttpServlet—This is the class that is most often extended when servlets are written. It extends GenericServlet to provide HTTP-specific processing. Because HTTP is so common, servlets that extend this class tend to be the easiest to write. Normally, you override the doGet(), doPost(), or both methods of this class. This class contains a default implementation of service() that calls the appropriate doXXX() method, depending on the type of request that is received.

  • ServletRequest—This interface defines an object that contains the information that the client has provided, along with his request to run the servlet. A concrete implementation of this object is ServletRequestWrapper class.

  • HttpServletRequestWrapper—This is an extension of the ServletRequestWrapper that contains information specifically assuming that the request will be in HTTP format. In most servlets, this class is accessed polymorphically via a handle to the ServletRequest interface. See Chapter 7, "Inheritance," for information on how this works.

  • ServletResponse—This interface defines a convenient way for a servlet to communicate the information that it wants to send to the client to the servlet container. A concrete implementation of this object is ServletResponseWrapper class.

  • HttpServletResponseWrapper—This is an extension of the ServletResponseWrapper that assumes that the response will be in HTTP format. In most servlets, this class is accessed polymorphically via a handle to the ServletResponse interface.

Programming Generic Servlets

Even though most of this chapter will deal with HTTP-based servlets, it is useful to understand how a servlet can be created that is not tied to this protocol. Listing 21.1 shows a simple generic servlet.

Listing 21.1 The GenericHello Class

/*
 * GenericHello.java
 *
 * Created on June 21, 2002, 5:28 PM
 */


import javax.servlet.*;
import java.io.*;

/**
 *
 * @author Stephen Potts
 * @version
 */
public class GenericHello extends GenericServlet
{
  
  /** Initializes the servlet.
   */
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config); 
    
  }
  
  /** Destroys the servlet.
   */
  public void destroy()
  {
    
  }
  
  public void service(ServletRequest req, ServletResponse resp)
  throws ServletException, java.io.IOException
  {
    resp.setContentType("text/html");
    java.io.PrintWriter out = resp.getWriter();
    out.println("Hello from the GenericHello Servlet");
    out.close();
  }
  
  /** Returns a short description of the servlet.
   */
  public String getServletInfo()
  {
    return "This servlet tests the GenericServlet class";
  }
  
}

Notice that this class extends the GenericServlet class. As discussed previously, this is a protocol-neutral servlet class.

public class GenericHello extends GenericServlet

The init() method is overridden here. Notice that it is passed a ServletConfig class, which it passes along to the super(GenericServlet) class's init() method. The ServletConfig class contains references to the servlet name and the ServletContext object. For now, we can ignore these objects.

  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
  }

We override the destroy() method just for show.

  public void destroy()
  {
    
  }

We also override the getServletInfo() method so that you will have an example of how this is done.

  public String getServletInfo()
  {
    return "This servlet tests the GenericServlet class";
  }

Finally, the service() routine is where the action is, what little there is in this example.

  public void service(ServletRequest req, ServletResponse resp)
  throws ServletException, java.io.IOException
  {
    java.io.PrintWriter out = resp.getWriter();
    out.println("Hello from the GenericHello Servlet");
    out.close();
  }

We create a handle to the response object's PrintWriter object so that we can send some information to the client. We are not interested in any of the information available from the client in this simple example. We print a string to this object, and then close it. The servlet container is responsible for actually getting the string to the client.





Page 2 of 9



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel