How to build a Java servlet, small example

It is a small web application written in Java, running on the server and interacting with the remote client. It sends to the client data in HTML or another format.
The client can access it from the browser with a URL. It runs in a special server, a servlet container.

A servlet container is a specialized web server and a runtime environment for servlets it contains, which provides the API of classes and methods they can use. There are examples of those classes below.
The best known is Apache Tomcat (different from the Apache server), which is also an HTTP server.
It is also known as web container or web engine. Besides Tomcat may be added Jetty, Geronimo, Winstone, Jaminid.
JBoss encapsulates Tomcat.

Here is an example of a minimalist servlet...

Hello World! displayed by a servlet:

package demo;

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

public class HelloServlet extends HttpServlet 
{
  public void doGet (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException  
    {
      PrintWriter out = res.getWriter();
      out.println("Hello, world!");
      out.close();
  }
}

Get the Java source code.

Another example provided by Apple that creates a web page:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.rmi.*;


public class HelloWorldServlet extends HttpServlet 
{
    private HelloWorld hw = null;
    public HelloWorldServlet() throws NamingException
    {
        Context ctx = new InitialContext();
        HelloWorldHome home = (HelloWorldHome)
        PortableRemoteObject.narrow(ctx.lookup("HelloWorld"),
        HelloWorldHome.class);
        try { this.hw = home.create();  }  catch (Exception e) { }
    }
   public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
   {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.println("<html>");
       out.println("<head>");
       out.println("<title>Demo</title>");
       out.println("</head>");
       out.println("<body>");
       out.println("<h1>Hello World!</h1>");
       out.println(this.hw.hi());
       out.println("</body>");
       out.println("</html>");
   }
}

Download the complete source code.

This servlet generates the following HTML page:

<html>
<head>
    <title>Demo</title>
</head>
<body>
   <h1>Hello World!</h1>
   ... content from the user...
</body>
</html>

Reference: Java Servlet Technology Overview. Various downloads are offered including the specification.