First we need something to pick up files and send them over the wire. NanoHTTPD fits the bill for a small starter application. Created in Java using a single file and only a port as command-line options, you can’t get simpler than this. With a generous BSD license it is easily extendable to suit my purpose at the low end of web site resource creation.
As we add modules to Nano it is best to keep in mind how larger web servers work to keep the code reusable. For instance Servlets are very popular on large web sites using J2EE. Popular ones are Tomcat, Glassfish, and Jboss. Staying with our open-source theme, Glassfish from Sun, now Oracle, seems to be a good choice, but as they all support J2EE standards it should be easy to keep our code generic to work across the board.
As for databases, JavaDB is a good candidate for the low end, Sqllite is the preferred method for Smartphones and HTML5, while Oracle is a winner at the large scale for Relational Management. The are many other NOSQL alternatives such as CouchDB and Cassandra, but again if we keep the DB abstract enough, it should be easy to switch around.
In fact that is my whole theme, to be able to switch components in and out in true Object Oriented fashion. So we will start with a generic framework and start plugging in components.
There are four modes of operation:
1) Tiny (smartphone)
2) Medium (Laptop)
3) Large (Desktop)
4) Huge (Clustered servers)
I will start at medium, move to tiny, and then large.
NanoHTTPD can be:
Run as a standalone app, serves files from current directory and shows requests
Subclass serve() and embed to your own program
Call serveFile() from serve() with your own base directory
So we download NanoHTTPD.java, and compile it:
$ javac NanoHTTPD.java
Then run it:
$ java NanoHTTPD 8080
NanoHTTPD 1.21 (C) 2001,2005-2011 Jarno Elonen and (C) 2010 Konstantinos Togias
(Command line options: [port] [–licence])
Now serving files in port 8080 from “/Users/don/Documents/workspace/trutree/src/com/doncohoon/server”
Hit Enter to stop.
Now fire up your browser and enter URL => http://localhost:8080. You should see at least the source for NanoHTTPD.java and some class files. To run the web server on port 80, you will need to run as a privileged user (sudo java NanoHTTPD). This works on Mac OS X, Linux and Windows, except for Windows privileged user access require logging on as Administrator or granting your user Admin rights.
Congratulations! You now have a web server. Next we will build a database to house our dynamic content. Same Bat Channel next time, in Build-a-Website.