Articles Feed

Authors

Categories

MM-HTTP: Simple Java HTTP Server

by: micah | March 24th, 2009 |

Bloodroot seeds. They have nothing to do with this blog except that this was the first search result on flickr for ‘MM HTTP’. I think they’re quite interesting.

I was recently working on a Java project where I needed to serve up a couple pages via HTTP. These pages were nothing fancy but their content was purely dynamic. It’s also worth noting that the project was a shrink wrapped product.

The most immediate options that came to mind when I thought Java/Web were, Servlets, Struts, EJB, …. oh my! These options seemed like overkill. I didn’t want to complicated the deployment of this product with beasties like Tomcat and JBoss. That’s just silly. I wanted a simple web server that I could plug into my code and serve a couple dynamic pages. I took a quick peek at Jetty and thought “No thanks”.

Of course, all along I was thinking about FitNesse. FitNesse is a stand-alone web server. And it’s just a jar file. In fact, I have fond memories of writing the FitNesse HTTP server and it occurred to me how simple it would be to extract that module into a self contained library. So I did it. It was simple. And I call it MM-HTTP.

So how do you write a Hello World web app with MM-HTTP? Like this:

  1. import mmhttp.server.*;
  2. import mmhttp.protocol.*;
  3. public class HelloWorld
  4. {
  5. public static void main(String[] args) throws Exception
  6. {
  7. Server server = new Server(8000);
  8. server.register("hello.*", HelloResponder.class);
  9. server.start();
  10. }
  11. public static class HelloResponder implements Responder
  12. {
  13. public Response makeResponse(Server server, Request request) throws Exception
  14. {
  15. return new SimpleResponse(200, "<h1>Hello World!</h1>");
  16. }
  17. }
  18. }

You’ll need to download the mmhttp jar file. Once you’ve pasted the above code in a HelloWorld.java file, you can compile and run the web server like so:

  1. javac -classpath mmhttp-1.1.jar HelloWorld.java
  2. java -classpath mmhttp-1.1.jar HelloWorld

Then plug the following URL into your browser. http://localhost:8000/hello. That’s it!

To find out more, visit the MMHTTP github page and the javadocs. Enjoy!

Leave a Reply

#