A Java servlet that is also a stand alone program. And a server that is also a web client.
Archive - Originally posted on "The Horse's Mouth" - 2015-02-19 18:51:03 - Graham EllisI've been teaching the fundamentals of Java (a private 4 day course) to a number of groups over the past few weeks - each time tailoring the course towards the projects that the delegates (within a large organisation) will be using it for, and also tailoring to suite the background of the delegates. This week, my delegates turned out to be rather more experienced programmers than the earlier groups, an they have a target application that's web based. So on the final day - today - we took teaching examples that we had been working on and added a servlet interface.
The main application class is [here] and includes both a main method for it to run stand alone, and a doGet method for it to run as a servlet.
• In order to avoid code repetition, both the main and the doGet method call a protected action method.
• Since main is static and doGet is not, the main method creates an object on which it can run the action method.
• Both methods set up a PrintWriter for output; the main method explicitly closes it (otherwise buffers may not be flushed, and some data lost) and the doGet method does not close it (leaving it available to the Apache Tomcat server).
This program also contains an example of a Comparator class, since we sorted a whole collection of objects in a "non-natural" way - the natural way to sort places is alphabetically, but one of my delegates fancied sorting them from north to south - so that's what we did all the way from Thurso and Georgemas to Falmouth and Penzance. The comparator source code is [here].
The data used by this program is located on our main server, and so the servlet becomes itself a client to another web server, from which it reads the data URL. Our MyStream class - [here] - actually includes two constructors to open the data source stream - a single parameter version for a local file, and a two parameter version for a remove file via a web protocol, using a java.net.URL object and calling an openStream method on it. Polymorphic code then allows the same method readLine to read either locally or remotely.
The final source code in this example is our Station class - see [here]. You will note (if you've read some of the more blog articles posted earlier this week) that I'm re-using code. And that's exactly what I should be doing with Java - the initial developement of my classes may be a little more longwinded than it would be in Perl, Ruby or Python - but their robustness and reliability then makes them an excellent fit for the large projects being undertaken by this customer.