Software Steeplechase

Hayden Steep’s development obstacle course. (Java, JEE, and beyond)

October 25, 2006

Creating a servlet with a self-contained web server

Filed under: Java, JEE

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();
    }
}

2 Comments »

The URI to TrackBack this entry is: http://steep.blogsome.com/2006/10/25/creating-a-servlet-with-a-self-contained-web-server/trackback/

  1. If you had a normal Java Swing gui and the browser inside, how would you communicate between the swing app and the browser. E.g Say you wanted to save some form details using a menu file|save option. Or would it be better to have the menu within your JSP/Servlet??

    Comment by Ian Heffernan — June 29, 2007 @ 4:37 am

  2. Cool,

    Great article ,I like it that it is step by step

    Anyway, thanks for the post

    Comment by Web developer — August 20, 2009 @ 2:21 pm

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com