Jeff Miller

Team to Create Outside the Box

HTTP Server ContextHandler in a Jar


Last time I showed you how to create a basic HTTP Server that you can put into a JAR easily.  Today I’m going to show you how to extend that to include a ContextHandler and AbstractContextHandler to make it easier to create Handlers for your HTTP Server.  If you remember our properties file from before had a “Handlers” property which was a comma separated list of classes to load as ContextHandlers for our HTTP Server.

Those ContextHandlers are load and initialized in the HttpSystem.start() method.  It takes a ContextHandlerInterface.  Here is the implementation for that interface:


This is really a simple interface.  First notice it extends HttpHandler, this is important and our derived classes will need to implement that API which is a single HttpHandler.handle(HttpExchange exchange).  Next we have a method ContextHandlerInterface.getContext() for returning the Context of this handler.  This is important as our HttpSystem needs to know the URI this ContextHandler will be processing.  Next we have a method ContextHandlerInterface.getFilters() that returns any filters this context needs.  We will discuss those in another post later on.

Now we create an AbstractContextHandler to take care of some of the more mundane items that we don’t want to keep implementing.  Here is the code for AbstractContextHandler:

First thing to notice is that we implement the HttpHandler.handle(HttpExchange exchange) method.  It uses the implemented helper functions to determine the type of HTTP Request that is incoming, and calls out to stub functions based on type; HEAD, GET, POST, PUT, & DELETE.  All you need to do is override the methods your interested in and implement your code. Now we use an AdvancedString to determine if there is any HTML embedded in the URL, if so we abort the request and send an HTTP_BAD_REQUEST_STATUS.

Now your ready to implement your own ContextHandlers, by extending AbstractContextHandler, and implement the ContextHandlerInterface.getContext() & ContextHandlerInterface.getFilters() methods to provide your specifics.  Then override the doHead(), doGet(), doPost(), doPut(), and doDelete()  to implement the final pieces of your ContextHandler. You have multiple methods of sendResponse() to use for sending your response.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.