A Hello World servlet

A best-selling programming book on Amazon
The
Clean
Coder

Last week I was working with OpenSSO quite a bit, and at one point I just needed a really simple Java servlet that I could first try to run, and then try to secure, using OpenSSO. All I really needed for this purpose was a "Hello world servlet", and that's when I realized I've never put one out here.

So, to fix that problem, here is the source code for a very simple Java servlet that will print "Hello, world" when you access it through a browser. To get started, here's the source code for the servlet:

package com.devdaily.servlets;

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

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

If you've worked with servlets at all, you know that creating a servlet is at least a two-step process, and one of the other steps involves putting some configuration lines in your web.xml file. For my servlet, these are the lines I added to my web.xml file:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.devdaily.servlets.HelloWorldServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

Other than the whole part of compiling and deploying your application -- which is beyond the scope of this blog entry -- that's the source code you need for a very simple Java servlet.

The doPost method

If you really want to go crazy, you can also add a doPost method to this servlet, and have it do something like call the doGet method, but that's not really necessary.

“There is only Now.”
 
~ Eckhart Tolle

But, if you do want to do this for some reason, just add the doPost method to your class, so it looks something like this:

package com.devdaily.servlets;

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();
  }

  public void doPost (HttpServletRequest req,
                      HttpServletResponse res)
    throws ServletException, IOException
  {
    // just call the doGet method
    doGet(req, res);
  }
}

For this very simple example there's no reason to do anything like this, but I thought I'd show it, in case you ever want to do something like this for some other reason.