Search code examples
javaundertowundertowjaxrsserver

Undertow Routing Format using Wildcards


My requirement is to serve "index.html" irrespective of what route is being set in the request. I have referenced Routing template format for undertow but to no avail. It seems to work for people. The handler looks like

PathHandler path1 = Handlers.path()
            .addPrefixPath("/*", new ResourceHandler(new FileResourceManager(new File(System.getProperty("user.dir")+"ed.jpg"), 100 * 1024)).setWelcomeFiles("index.html") );

And the handler is being added like

server = Undertow
                    .builder()
                    .addHttpListener(serverConfig.getHttpPort(), serverConfig.getHost())
                    .addAjpListener(serverConfig.getAjpPort(), serverConfig.getHost())
                    .setHandler(path1)
                    .build();

I have tried using PathResourceManager as well. That doesn't work. The handler is able to match paths without wildcards perfectly. Only cases with wildcard character seems to fail.

Any help on this would be appreciated.


Solution

  • You do not want to use a PathHandler.

    Instead, serve your HTML file with a ResourceManager directly from a custom handler, like this:

    ResourceManager rm = new PathResourceManager(Paths.get("/path/to/your/folder"));
    Resource r = rm.getResource("index.html");
    Undertow.builder()
        .addHttpListener(8080, "0.0.0.0")
        .setHandler(Handlers.predicate(
            ex -> ex.getRequestMethod().equals(Methods.GET),
            ex -> r.serve(ex.getResponseSender(), ex, IoCallback.END_EXCHANGE),
            ResponseCodeHandler.HANDLE_405)
        ).build().start();
    

    Note1: I have added a simple check to the request verb/method with a predicate, to only allow GET requests and fallback to a simple 405 response.

    Note2: you might want to dispatch the handler that serves the HTML file to a worker thread.