October 24, 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 »

Deploying the Servlet

Under JDK 1.4, all the classes needed to compile this program are automatically installed. This makes it simple to compile the program. You just type the following at a command line:

javac GenericHello.java

The servlet is now compiled into a .class file in this same directory. If this were a garden-variety Java application, we could run it by typing the following:

java GenericHello
Exception in thread "main" java.lang.NoSuchMethodError: main

Being a servlet, this class has no main() method, and the Java runtime engine points that out to you by throwing an exception.

We could just go and type the name of this servlet in the address line of our browser, but that will give us an error message stating that the servlet container doesn't know anything about this servlet as shown in Figure 21.4.

Figure 21.4.

The Tomcat server doesn't know anything about this servlet, so it provides a polite error message.

We have a servlet container running, and we have a servlet that compiles. What we need is a way to tell the servlet container about this servlet. A good quick-hitter approach to this is to place the servlet in the ...\webapps\examples\WEB-INF\classes directory. After that is done, we can type the following URL in your browser's address field (with Tomcat running):

http://localhost:1776/examples/servlet/GenericHello

If you installed Tomcat using the default port of 8080, you would substitute "8080" for the "1776."

The examples string indicates that the GenericHello class is a servlet, and that its class file can be found under the examples subdirectory. Figure 21.5 shows the result of running GenericHello.

Figure 21.5.

The GenericServlet's output contains no formatting information.

Notice that the message is output to the screen in whatever font the browser chooses. This is done because we provided no input to the browser on how to format the results. This desire to have more control over the layout is the motivation for creating the HTTPServlet class.

Next, let's modify our example to use the HTTPServlet class so that we can have more control over the output. Listing 21.2 shows the code for the new servlet.

Listing 21.2 The HTTPHello Example

/*
 * HTTPHello.java
 *
 * Created on June 21, 2002, 9:59 AM
 */

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author Stephen Potts
 * @version
 */
public class HTTPHello extends HttpServlet
{
  
  /** Initializes the servlet.
   */
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config); 
    
  }
  
  /** Destroys the servlet.
   */
  public void destroy()
  {
    
  }
  
  /** Processes requests for both HTTP <code>GET</code>
   * and <code>POST</code> methods.
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, 
                  HttpServletResponse response)
  throws ServletException, java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>HTTPHello</title>");
    out.println("</head>");
    out.println("<body>");
    
    //Make the font large
    out.println("<H1>");
    //Make the font bold
    out.println("<B>");
    
    out.println("Hello from the HTTPHello Servlet");
    out.println("</H1>");
    out.println("</B>");
     
    out.println("</body>");
    out.println("</html>");
    out.close();
  }
  
  /** Handles the HTTP <code>GET</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doGet(HttpServletRequest request,
            HttpServletResponse response)
  throws ServletException, java.io.IOException {
    processRequest(request, response); 
  }
  
  /** Handles the HTTP <code>POST</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
  throws ServletException, java.io.IOException {
    processRequest(request, response);
  }
  
  /** Returns a short description of the servlet.
   */
  public String getServletInfo() {
    return "This is the HTTPHello Servlet";
  }
  
}

This servlet was created using the Forte for Java code editor, which generates an empty HTTPServlet for you. This can save you time when writing servlets, but it can retard learning. Until you become familiar with the purpose of every line of code in this example, any tools will hamper learning. After you can write servlets in your sleep, the tools will speed up your coding a little.

Notice that we now have an extra import statement. This package will give us HTTP processing.

import javax.servlet.http.*;

This servlet extends HTTPServlet. This will impact us because we will be overriding doGet() and doPost() instead of service().

public class HTTPHello extends HttpServlet

We have overridden the doGet() and doPost() methods in a unique fashion.

  protected void doGet(HttpServletRequest request,
                 HttpServletResponse response)
  throws ServletException, java.io.IOException
  {
    processRequest(request, response);
  }

  protected void doPost(HttpServletRequest request,
                 HttpServletResponse response)
  throws ServletException, java.io.IOException
  {
    processRequest(request, response);
  }

In both cases we simply made a call to a method that we named processRequest() and passed the request and response objects to it. There is nothing special about the name processRequest(). We could have called it xyz(). Later in this chapter we will look at the HTTP protocol and the difference between the Get and Post commands.

The real work in our example is now done in the processRequest() method. This method is passed in both an HttpServletRequest object and an HTTPServletResponse object.

  protected void processRequest(HttpServletRequest request,
                     HttpServletResponse response)
  throws ServletException, java.io.IOException {

These will be used extensively in future examples, but for now, we only use the response object.

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

We use the PrintWriter object to put data into the response object for transmission back to the client. Notice that HTML code makes up the contents of the string.

    out.println("<html>");
    out.println("<head>");
    out.println("<title>HTTPHello</title>");
    out.println("</head>");
    out.println("<body>");
    

We add this line to make the font large.

    out.println("<H1>");

This line makes the font bold.

    out.println("<B>");

This line contains the contents of what we want displayed.

    out.println("Hello from the HTTPHello Servlet");

The result of running this is similar to when we ran the GenericHello servlet, as shown here in Figure 21.6.

Figure 21.6

The HTTPServlet enables us to format our output by using HTML commands.





Page 3 of 9



Comment and Contribute

 


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

 

 


Sitemap | Contact Us

Rocket Fuel