Creating a servlet with a self-contained web server
For those of us who haven’t become guru’s at developing user interfaces in Swing/SWT/.NET or other technologies used to develop GUI’s, (in other words web developers), there is an easy way to leverage your JEE skills to create stand alone programs. Just create a web application as you normally would, but instead of deploying your creation to an application server, deploy the application server to your application.
Jetty WebServer is one such application server that can be instantiated inside of a Java program and configured to handle web requests on a certain port. When your application has completed its task, just stop the web server and your super-servlet will exit.
Here are the 4 basic steps to turning your server application development skills into client-application development skills.
Step 1: Constructor
The constructor instantiates an instance of the Jetty embeddable web server. It adds itself as the servlet that should handle all incoming requests on port 8111. It then starts the server.
private Server server;
private Context context;
public ExecServlet() {
server = new Server(8111);
context = new Context(server, "/", Context.SESSIONS);
context.addServlet(new ServletHolder(this), "/*");
try {
server.start();
}
catch(Exception e) {
e.printStackTrace();
}
}
Step 2: Get/Post functionality
In the methods below is where your servlet will do whatever it is you want it to do. The programmer has the full power of the Java API and libraries at his disposal in order to launch a process, process user input, write files, etc.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getPathInfo().equals("/DoSomething")) {
//Do Something and return a response.
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getPathInfo().equals("/PostSomething")) {
//Do Something and return a response.
}
}
Step 3: Executing
The servlet’s main() method instantiates an instance of itself and then launches a browser to point to itself. The code in the example is Windows specific, but some conditionals and a check of system properties can make the servlet operational in other operating systems.
public static void main(String[] args) {
ExecServlet servlet = new ExecServlet();
Runtime runtime = Runtime.getRuntime();
String[] cmd = new String[4];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = "start";
cmd[3] = "http://localhost:8111/";
try {
runtime.exec(cmd);
}
catch (IOException e) {
e.printStackTrace();
}
}
Step 4: All Done
Some process or user created condition will signal that the application has completed running, and now it is time to close up shop and stop the web/application server.
if (request.getPathInfo().equals("/finish")) {
try {
server.stop();
}
catch (Exception e) {
e.printStackTrace();
}
}


