8.3 Create the servlet

Under the classes/mydemo directory create the DemoServlet class:

package mydemo;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

public class DemoServlet
        extends HttpServlet
{
    /**
     *  Called once at startup
     */
    public void init()
        throws ServletException
    {
        System.out.println("Init() the Servlet");
    }

    public void doGet( HttpServletRequest req, HttpServletResponse resp )
        throws ServletException, IOException
    {
        String name = req.getParameter("name");

        // Handle a null
        if ( name == null )
        {
            name = "You forget to add name.";
        }

        // Set the content type
        resp.setContentType("text/html");

        // Generate the HTML
        String output = getOutput(name);

        // Write to the browser
        PrintWriter writer = null;
        try
        {
            writer = resp.getWriter();
            writer.write(output);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            writer.flush();
            writer.close();
        }
    }

    private String getOutput( String name )
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("<html><body><h2>Hello. Your name is: ");
        buffer.append(name);
        buffer.append("</h2></body></html>");

        return buffer.toString();
    }
}
Compile the servlet ( make sure you have the servlet.jar in your classpath ).