Routing (including handlers)
To understand how the routing works, a quick introduction to the code flow is provided below:
code flow
synapticloop.nanohttpd.RouteMasterServer
is instantiated and listens on the defined port (default 5474), and the defined host (default 127.0.0.1). All incoming requests then invoke theRouteMaster.route
method.synapticloop.nanohttpd.router.RouteMaster.route(File rootDir, IHTTPSession httpSession)
is invoked for EVERY request. This will determine which router should be invoked for the incoming request. To determine which router to invoke, the following flow is followed:- If the route is cached, then the router is known and is invoked.
- If the route is not cached, then the
synapticloop.nanohttpd.router.Router.route
method is invoked, which will return the assigned router
synapticloop.nanohttpd.router.Router.route(IHTTPSession httpSession, StringTokenizer stringTokenizer)
is invoked to determine which router should handle the incoming request. This will walk the URL path until a suitable router is found.serveResource(File rootDir, IHTTPSession httpSession)
depending on which router is found, this method is invoked, and depending on the functionality of the implementation, will depend on whetherHandler
s are theninvoked.- In the instance of the
synapticloop.nanohttpd.servant.ClasspathFileServant
, the handlers are then consulted as to whether they will be able to handle the request. If so, theHandler
will be invoked before theServant
. Note that each implementation may work differently, and use the local file before invoking theHandler
.
Wildcard routes
Wildcard routes allow you to bind a specific router to multiple URLs. The simplest example is the:
route./*=synapticloop.nanohttpd.servant.StaticFileServant
Which binds the root of the site (i.e. /
) and all paths beyond it that are not bound to any other route. Contrast this with the following:
route./=synapticloop.nanohttpd.servant.StaticFileServant
Which only binds the root of the site to the StaticFileServant
and no other routes.
In fact, if you only wanted to spin up a static file web server, you could use the above route (route./*=synapticloop.nanohttpd.servant.StaticFileServant
) and that is all that would be needed.
To understand the different types of routers, have a look at the simple routes andRESTful routes documentation.
Handlers
Handlers are implementation specific and work on an extension basis, i.e. handlers are mapped to specific extensions. If a file exists on either the filesystem or classpath which may either be served the Servant
or Handler
, then the precedence from a syanpticloop convention should use the Handler
first.
However: It must be noted that whilst synapticloop observes this convention, it is not a pre-requisite and other Handler
s may use differing conventions and favour the local resource.