Roman N
Roman N

Reputation: 5110

Simple rest with undertow

I have this code for server:

Undertow server = Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler(Handlers.path()
                .addPrefixPath("/item", new ItemHandler())
        )
        .build();
server.start();

And handler:

private class ItemHandler implements HttpHandler {

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
        exchange.getPathParameters(); // always null
        //ItemModel item = new ItemModel(1);
        //exchange.getResponseSender().send(mapper.writeValueAsString(item));
    }
}

I want to send request /item/10 and get 10 in my parameter. How to specify path and get it?

Upvotes: 8

Views: 6394

Answers (1)

ant1g
ant1g

Reputation: 1009

You need a PathTemplateHandler and not a PathHandler, see:

Undertow server = Undertow.builder()
    .addHttpListener(8080, "0.0.0.0")
    .setHandler(Handlers.pathTemplate()
        .add("/item/{itemId}", new ItemHandler())
    )
    .build();
server.start();

Then, in your ItemHandler:

class ItemHandler implements HttpHandler {

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
      exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

      // Method 1
      PathTemplateMatch pathMatch = exchange.getAttachment(PathTemplateMatch.ATTACHMENT_KEY);
      String itemId1 = pathMatch.getParameters().get("itemId");

      // Method 2
      String itemId2 = exchange.getQueryParameters().get("itemId").getFirst();
    }
}

The method 2 works because Undertow merges parameters in the path with the query parameters by default. If you do not want this behavior, you can use instead:

Handlers.pathTemplate(false)

The same applies to the RoutingHandler, this is probably what you want to use eventually to handle multiple paths.

Handlers.rounting() or Handlers.routing(false)

Upvotes: 9

Related Questions