Monday, January 12, 2009

Beyond web.xml

Another day paying the bills in Eclipse...
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("Hello World!");

So you've just written yourself a spiffy little servlet and you want to test it out. That's when it hits you... there is a long and arduous road ahead. You've got to remember how to deploy a War (how does that Ant script go again?). You need to configure Tomcat (Or wait 20 minutes for Weblogic to start). Then you need to write that dreaded web.xml file. This is a barren wasteland, riddled with fire and ash and dust. The very air you breathe is a poisonous fume. Not with ten thousand men could you do this. Tis folly!

Dag-nabbit! You aren't writing a big fancy industrial strength web app. All you want to do is run your little servlet in a local web browser and get on with your life! Jiminy Cricket, it's times like this that can turn a developer to Rails.

So what are you going to do? Bite the bullet and muddle through it all for the umpteenth time? Give up and write a command line app? Recall that the three chief virtues of a programmer are: Laziness, Impatience, and Hubris. Where there is a will, there is a way.

Grab yourself a Jetty jar and throw one of these in your app:
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class EmbeddedServletRunner {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
Context root = new Context(server,"/",Context.SESSIONS);
root.addServlet(new ServletHolder(new HelloWorldServlet()), "/hello");
Run it. Point your browser to http://localhost:8080/hello and you're good to go.