Getting started with servlet development: a skeleton servlet

We'll assume that you've obtained the necessary things to compile and run a servlet as outlined in our servlet tutorial introduction. You should generally set up your project to compile against the Enterprise edition of Java, so that it finds the servlet classes in javaee.jar.

Then, creating a basic servlet is as simple as creating an extension of the class HttpServlet with the following methods defined:

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

public class BasicServlet extends HttpServlet {
  
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();
    // ... output page to pw...
  }

  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    doGet(req, res);
  }

}

So far, this example doesn't actually output any HTML, but it shows the basic anatomy of a servlet class. We extend HttpServlet and must provide implementations of the two methods. These methods correspond to HTTP get and post methods respectively. As discussed in the latter link, you can generally make doPost() simply pass the request to doGet(). To the servlet, both types of request essentially look the same. For example, parameters will be extracted from either a URL or POSTed data.

HttpServletRequest and HttpServletResponse

Via these objects, you can find out about the user's request, and write the response. The request object allows you to query things such as:

You can also query the request method, in case your program "forgets" whether it was called via doGet() or doPost() and subsequently needs to know.

With the response object, you can:

Outputting an HTML page

The simplist way to output a page of HTML is using the PrintWriter as follows:

  private String message =
    "Welcome to the Orthogonal Terwilliger Accordion Association!";
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();
    pw.println("<html>");
    pw.println("<body>");
    pw.println("<p>" + msg + "</p>");
    pw.println("</body>");
    pw.println("</html>");
  }

Obviously, in practice we would want to send a <head> section just like any other web page.

And for very basic web pages, that's it! However, for non-trivial cases, you will generally want to do at least some of the following: